Adding time to jQuery UI Datepicker
For some work I’m doing right now I needed the current time output into the input field that the (excellent) jQuery datepicker uses, but I don’t need it selectable by the user. The default format is
mm/dd/yyyy
but can be formatted using the formatDate parameter. The list of formatting options is considerable, including predefined setups for ATOM, COOKIE, ISO_8601, various RFC dates, RSS, TIMESTAMP and even W3C. Unfortunately none of the predefined formats, nor the large list of date components includes time.
As I sat for a moment reading over the list I noticed
‘...’ - literal text
Aha! Those jQuery folks… gotta love them. If only javascript date manipulation wasn’t so crumby. The current solution, while nicely functional, offends the sense of javascript elegance that jQuery has blessed/cursed me with. If anyone has solutions for improvements to this code, I’d be all ears! I mean really… an if statement to get AM or PM?
date_obj = new Date();
date_obj_hours = date_obj.getHours();
date_obj_mins = date_obj.getMinutes();
if (date_obj_mins < 10) { date_obj_mins = "0" + date_obj_mins; }
if (date_obj_hours > 11) {
date_obj_hours = date_obj_hours - 12;
date_obj_am_pm = " PM";
} else {
date_obj_am_pm = " AM";
}
date_obj_time = "'"+date_obj_hours+":"+date_obj_mins+date_obj_am_pm+"'";
$("#entry_date").datepicker({dateFormat: $.datepicker.W3C + date_obj_time});


Pascal wrote on
I think some clever use of everyones favorite mod() function could solve your if problem.
date_obj_am_pm = (date_obj_hours < 12) ? 'AM': 'PM';
// This turns midnight into 12 AM, so ignore if it's already 0
if (date_obj_hours != 0) {
date_obj_hours = ((date_obj_hours + 11) % 12) + 1;
}
That should do it.