I'm maintaining an application which uses the jQuery UI Timepicker and trying to troubleshoot a bug.
Basically, this is how to re-create it:
There are 2 timepickers, start time and end time
1. on the start-time, select 6:00am (from the hour area)
2. on the end-time, select 12:00pm (from the hour area)
3. go back to the start-time and select 00 from the minute area
Then some code runs to determine the elapsed time in minutes. That code is:
function setDuration() {
var $startTime = $(".field.times input[name$='StartTime']");
var $endTime = $(".field.times input[name$='EndTime']");
var $durationHours = $(".field.duration input[name$='DurationHours']");
var $durationMinutes = $(".field.duration input[name$='DurationMinutes']");
if ($startTime.val() != "" && $endTime.val() != "") {
var startTime = $startTime.timepicker ? $startTime.timepicker('getTimeAsDate') : Date.parse('01 jan 01 ' + $startTime.val(), "hh:mm tt");
var endTime = $endTime.timepicker ? $endTime.timepicker('getTimeAsDate') : Date.parse('01 jan 01 ' + $endTime.val(), "hh:mm tt");
var duration = (endTime - startTime) / 1000 / 60;
//check whether spanning multiple days
if (startTime > endTime) {
duration = duration + (60 * 24);
}
$durationHours.val(Math.floor(duration / 60));
$durationMinutes.val(duration % 60);
}
}
I have found that after completing steps 1 and 2, everything is fine.
But, if I complete step 3, the endTime local variable is assigned a date object which has a time component of 11:59 and not 12:00.
Off by 1 minute.
If I then go to the End Time picker and select 00 from the minute area, as I did with the Start Time picker, the elapsed time rights itself again.
As an interesting observation when debugging, both timepickers are 1 minute behind after steps 1 and 2. That is, they are at 5:59 and 11:59. The elapsed time is correct, as the difference is important. But as a said, as soon as a user selects 00 from the hours area, it seems to "right itself" for that picker and the difference is out by 1 minute (until the same thing is done for the other picker).
Javascript dates are hard! Help would be great.
Yeah, figured it out. I guess it is an opinionated component which holds the opinion that the user must select a minutes figure from the minutes area. Because if they don't, the minutes will be -1.
Fair enough.
To fix this bug, in the onSelect handler, I wrote some code similar to this:
In our app, if they don't select '00' or any other minutes, it will be presumed to be 0.