Reputation: 745
I have a form containing two input type="time" fields. I have a third input type="time" field called 'delay' on the form that I would like to use jQuery to update based on the difference between the two times.
I have searched for an answer but so far have not been able to come up with a solution that works. Since the input type="time" fields only contain hours/minutes I've tried something like this:
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
var timeOfCall = $('#timeOfCall').val();
var timeOfResponse = $('#timeOfResponse').val();
var diff = new Date("Aug 08 2012" + timeOfCall) - new Date("Aug 08 2012" + timeOfResponse);
var timeDifference = diff/(60*60*1000);
However this does not work. I get NaN responses when I use this. I got this code from another Stackoverflow question and the person who asked the question there also got the same NaN issue, but unhelpfully found a solution to the problem without posting what it was.
I've also tried this:
var timeDifference = new Date("1970-1-1 " + timeOfCall) - new Date("1970-1-1 " + timeOfResponse) ) / 1000 / 60 / 60;
This definitely comes the closest to working but it gives some odd results sometimes. For instance, if timeOfCall is 01:01 and timeOfResponse is 03:03 it gives a difference of 2.033333....
In either case I also cannot get the 'delay' time field to update in either case.
$('#delay').val(timeDifference);
Simply does nothing. I would really appreciate any and all assistance with this, I have been going at it for the past few days with no success and no real clue how to go about fixing it. I've been doing a lot of Googling but very few results actually seem to pertain to HTML5 input type="time" fields so I've had no luck so far.
Edit: jsFiddle
Upvotes: 0
Views: 5349
Reputation: 74420
Could be just like that:
$('button').on('click', function () {
var timeOfCall = $('#timeOfCall').val(),
timeOfResponse = $('#timeOfResponse').val(),
hours = timeOfResponse.split(':')[0] - timeOfCall.split(':')[0],
minutes = timeOfResponse.split(':')[1] - timeOfCall.split(':')[1];
minutes = minutes.toString().length<2?'0'+minutes:minutes;
if(minutes<0){
hours--;
minutes = 60 + minutes;
}
hours = hours.toString().length<2?'0'+hours:hours;
$('#delay').val(hours + ':' + minutes);
});
Upvotes: 2