3 回答
TA贡献1821条经验 获得超4个赞
凑合。减去JavaScript Date对象以获得它们的区别:
// use a constant date (e.g. 2000-01-01) and the desired time to initialize two dates
var date1 = new Date(2000, 0, 1, 9, 0); // 9:00 AM
var date2 = new Date(2000, 0, 1, 17, 0); // 5:00 PM
// the following is to handle cases where the times are on the opposite side of
// midnight e.g. when you want to get the difference between 9:00 PM and 5:00 AM
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
您可以将字符串转换为24小时格式,如下所示:
function parseTime(s) {
var part = s.match(/(\d+):(\d+)(?: )?(am|pm)?/i);
var hh = parseInt(part[1], 10);
var mm = parseInt(part[2], 10);
var ap = part[3] ? part[3].toUpperCase() : null;
if (ap === "AM") {
if (hh == 12) {
hh = 0;
}
}
if (ap === "PM") {
if (hh != 12) {
hh += 12;
}
}
return { hh: hh, mm: mm };
}
parseTime("12:00 AM"); // {hh: 0, mm: 0}
parseTime("12:00 PM"); // {hh: 12, mm: 0}
parseTime("01:00 PM"); // {hh: 13, mm: 0}
parseTime("23:00"); // {hh: 23, mm: 0}
TA贡献1795条经验 获得超7个赞
此函数返回一个字符串,其中包含与datetime字符串和当前日期时间的差异。
function get_time_diff( datetime ){ var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456"; var datetime = new Date( datetime ).getTime(); var now = new Date().getTime(); if( isNaN(datetime) ) { return ""; } console.log( datetime + " " + now); if (datetime < now) { var milisec_diff = now - datetime; }else{ var milisec_diff = datetime - now; } var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24)); var date_diff = new Date( milisec_diff ); return days + " Days "+ date_diff.getHours() + " Hours " + date_diff.getMinutes() + " Minutes " + date_diff.getSeconds() + " Seconds";}
在谷歌浏览器中测试console
(按F12)
get_time_diff()1388534523123 1375877555722"146 Days 12 Hours 49 Minutes 27 Seconds"
TA贡献1873条经验 获得超9个赞
这是适用于我的解决方案:
var date1 = new Date("08/05/2015 23:41:20");var date2 = new Date("08/06/2015 02:56:32");var diff = date2.getTime() - date1.getTime();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;alert(hh + ":" + mm + ":" + ss);
添加回答
举报