今天遇到需要计算一个距离开场时间相差了多少时间的需求:
var date = new Date(), year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate(), hours = date.getHours(), minutes = date.getMinutes(), seconds = date.getSeconds(); month = month<10?'0'+month:month; day = day<10?'0'+day:day; hours = hours<10?'0'+hours:hours; minutes = minutes<10?'0'+minutes:minutes; seconds = seconds<10?'0'+seconds:seconds; var startTime = new Date(year + '/' + month + '/' + day + '/' + ' 09:00:00'); //开始时间戳 var endTime = new Date().getTime() - startTime.getTime(); //当前时间减去开始时间相差毫秒数 alert(MillisecondToDate(endTime));//输出转换成时间格式
function MillisecondToDate(msd) { var time = parseFloat(msd) / 1000; if (null != time && "" != time) { if (time > 60 && time < 60 * 60) { time = getzf(parseInt(time / 60.0)) + ":" + getzf(parseInt((parseFloat(time / 60.0)) - getzf(parseInt(time / 60.0)) * 60)) + ""; } else if (time >= 60 * 60 && time < 60 * 60 * 24) { time = getzf((parseInt(time / 3600.0))) + ":" + getzf(parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) + ":" + getzf(parseInt((parseFloat((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) - parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) * 60)) + ""; } else { time = parseInt(time) + ""; } } return time; } //补零 function getzf(num){ if(parseInt(num) < 10){ num = '0'+num; } return num; }