Add hour to datetimepicker

David Carr

2 min read - 2nd Apr, 2015

When working with dates and forms I like to use datepickers, these allow the users to use a calendar to pick a date and have the date in the format mysql can store. I recently had a need to alter the time from a date and time picker, for instance selecting a from date and time, it would be very useful to be able to copy the chosen date and time into another input but with the time increasing by one hour. 

Download: https://github.com/daveismynamecom/addhourtodatetimepicker

Demo: https://demos.dcblog.dev/addhourdatetimepicker

jQuery makes this easy to do. Start with the input’s a from and to the important part is the id, the id is what jQuery will use to read from and update.

<p>From:<br><input id='from' name='from' class='datetimepicker' type="text" value="" /></p>
<p>To:<br><input id='to' name='to' class='datetimepicker' type="text" value="" /></p>

The datepicker used is from http://trentrichardson.com/examples/timepicker/ it requires jQuery and jQuery UI to be included. 

To call the datetimepicker:

$('body').on('click', '.datetimepicker', function() { $(this).not('.hasDateTimePicker').datetimepicker({changeMonth: true,changeYear: true,dateFormat: "yy-mm-dd",timeFormat: 'HH:mm:00',yearRange: "1900:+10",showOn:'focus'}).focus(); });


<p>This enables a class datetimepicker to be used on any input to show the picker.</p>

<p>Next used #from as the identifier read it&rsquo;s contents and create a new javascript date from the input date, break it down into month,year,day,hour,minute and seconds parts to then put the new formatted date together.</p>

<p>The slices used are to ensure single digits are always double digits. The hour is increased by 1 using +1 on the end of the hour variable.&nbsp;</p>

<p>Finally the new date is added to the input with an id of to</p>


<code class="language-javascript">//update date with an id of from into an id of to
$('#from').change(function () {
    var d = $('#from').val();
    d = new Date(d);

    var month = ('0' + (d.getMonth()+1)).slice(-2);
    var year = d.getFullYear();
    var day = ('0'+d.getDate()).slice(-2);

    var hour = d.getHours()+1;
    var min = ('0'+d.getMinutes()).slice(-2);
    var sec = ('0'+d.getMilliseconds()).slice(-2);

    newdate = year+'-'+month+'-'+day+' '+hour+':'+min+':'+sec;
    $('#to').val(newdate);
});

 

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.