How can I Add Time to a Date in jQuery

Laxmidi picture Laxmidi · Nov 16, 2011 · Viewed 9.1k times · Source

How do I add 23 hrs 59 min. 59 secs to end_date?

var end_date = jQuery('#end_date_datepicker').datepicker('getDate');
//pseudo-code:  end_date = (end_date + 23:59:59) 

I was thinking of trying to convert it to milliseconds, add 86 399 000 milliseconds, and then convert it back to time. But, I can't get it to work.

Answer

mu is too short picture mu is too short · Nov 16, 2011

The getDate method returns a JavaScript Date object so just add one day and remove one second:

var end_date = jQuery('#end_date_datepicker').datepicker('getDate');
end_date.setDate(end_date.getDate() + 1);
end_date.setSeconds(end_date.getSeconds() - 1);

The Date object will take care of adjusting everything to maintain a valid date. You could also manipulate the hours, minutes, and seconds on their own if you wanted.