我试图获得两次不同时间之间的时差,我正确地得到它几小时和几分钟。但如果第二个比第一个大,那么它就会出现问题。时间显示为负数据。
例如
Start time : 00:02:59
End time : 00:05:28
如果我得到开始和结束时间之间的差异
00:05:28 - 00:02:59 = 00:3:-31
这不是正确的值。我正在使用以下脚本来获取此值。
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);
任何人都请告诉我如何正确地计算两次之间的时差,即使考虑秒数
答案 0 :(得分:-6)
尝试这样做
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)
然后您可以将毫秒转换为小时,分钟和秒,如下所示:
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