Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

jquery - How to calculate the difference between 2 HTML5 time input types

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Could be just like that:

DEMO

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...