假设我有以小时为单位的变量日期:分钟:第二种格式
var time1 = "12:34:19 PM"
var time2 = "12:29:25 PM"
我如何从时间1和时间2获得差异(持续时间)?以及我们如何将其更改为日期格式以进行差异处理?
答案 0 :(得分:1)
您可以将新日期()的时间转换为前一个日期和
之前的日期使用getTime()
获取时间戳并减去它们
var duration = new Date('datetime1').getTime() - new Date('datetime2').getTime()
因为时间戳是结果总数的1000倍,所以将它除以1000
var duration = durantion/1000;
我只是创建一个正确格式化秒数的函数,使其看起来像一个有效的持续时间
var time1 = "2016-11-02 12:34:19 PM"
var time2 = "2016-11-02 12:29:25 PM"
time1 = new Date(time1 ).getTime();
time2 = new Date(time2 ).getTime();
var duration = (time1 - time2) / 1000;
function formatTime(seconds) {
var minutes = Math.floor(((seconds/3600)%1)*60);
minutes = (minutes < 10) ? '0'+minutes : minutes;
var seconds = Math.round(((seconds/60)%1)*60);
seconds = (seconds < 10) ? '0'+seconds : seconds;
return minutes+':'+seconds;
}
console.log('Duration: ' + formatTime(duration)+' secs')
答案 1 :(得分:0)
这是工作脚本
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
var timeStart = new Date("Mon Jan 01 2007 11:00:00 GMT+0530").getTime();
var timeEnd = new Date("Mon Jan 01 2007 11:32:51 GMT+0530").getTime();
var hourDiff = timeEnd - timeStart; //in ms
var secDiff = (hourDiff / 1000).toString(); //in s
alert(secDiff .toHHMMSS());
答案 2 :(得分:0)
您可以使用如下构造函数创建Date
个对象:
Date(year, month, date, hours, minutes, seconds, ms)
在你的情况下你可以得到差异:
var date = new Date(2000, 1, 1, 12, 34, 19, 0, 0),
date2 = new Date(2000, 1, 1, 12, 39, 25, 0, 0);
console.log(date2 - date); // in ms. You can do whatever you want with this value
您可以阅读有关Date
对象here.