Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Add hour to datetimepicker

David Carr

Javascript Tutorials HTML

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 source files

Demo

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();
 });

This enables a class datetimepicker to be used on any input to show the picker.

Next used #from as the identifier read it’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.

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. 

Finally the new date is added to the input with an id of to

//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);
});

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.