Html 在javascript中获取两次之间的时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18441698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting time difference between two times in javascript
提问by Kalai
I have tried to get the time difference between 2 different times and i am getting it correctly for hours and minutes. But if the second is greater than the first it will getting the problem. The time is displaying with negative data.
我试图获得 2 个不同时间之间的时差,并且我正确地获得了数小时和数分钟的时间。但是,如果第二个大于第一个,则会出现问题。时间显示为负数。
for example
例如
Start time : 00:02:59
End time : 00:05:28
If i getting the difference between start and end time
如果我得到开始时间和结束时间之间的差异
00:05:28 - 00:02:59 = 00:3:-31
Which is not a correct value. I'm using the following script for getting this value.
这不是一个正确的值。我正在使用以下脚本来获取此值。
var start_time = $("#startTime").val();
var end_time = $("#endTime").val();
var startHour = new Date("01/01/2007 " + start_time).getHours();
var endHour = new Date("01/01/2007 " + end_time).getHours();
var startMins = new Date("01/01/2007 " + start_time).getMinutes();
var endMins = new Date("01/01/2007 " + end_time).getMinutes();
var startSecs = new Date("01/01/2007 " + start_time).getSeconds();
var endSecs = new Date("01/01/2007 " + end_time).getSeconds();
var secDiff = endSecs - startSecs;
var minDiff = endMins - startMins;
var hrDiff = endHour - startHour;
alert(hrDiff+":"+minDiff+":"+secDiff);
anyone please tell me how to get the time difference between two times correctly even considering with seconds
任何人都请告诉我如何正确获得两次之间的时差,即使考虑秒
回答by Bittu
Try doing this
尝试这样做
var date1 = new Date(2000, 0, 1, 9, 0); // 9:00 AM
var date2 = new Date(2000, 0, 1, 17, 0); // 5:00 PM
if (date2 < date1) {
date2.setDate(date2.getDate() + 1);
}
var diff = date2 - date1;
// 28800000 milliseconds (8 hours)
You can then convert milliseconds to hour, minute and seconds like this:
然后,您可以将毫秒转换为小时、分钟和秒,如下所示:
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
// diff = 28800000 => hh = 8, mm = 0, ss = 0, msec = 0