检查Javascript中的时间差如何检查Javascript中两个文本框的时间差?
3 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
Date
// use a constant date (e.g. 2000-01-01) and the desired time to initialize two datesvar date1 = new Date(2000, 0, 1, 9, 0); // 9:00 AMvar 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 AMif (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
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贡献1825条经验 获得超6个赞
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
get_time_diff()1388534523123 1375877555722"146 Days 12 Hours 49 Minutes 27 Seconds"
米脂
TA贡献1836条经验 获得超3个赞
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);
添加回答
举报
0/150
提交
取消