以分钟为单位比较两个时间戳 JS

use*_*040 4 javascript time

嗨,我正在使用这个时间戳:

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}
Run Code Online (Sandbox Code Playgroud)

并在此处节省暂停时间:

localStorage["TmpPause"] = getTimeStamp();
Run Code Online (Sandbox Code Playgroud)

过了一会儿阅读时间并进行比较:

var pauseTime = localStorage["TmpPause"];
    var resumeTime = getTimeStamp();

    var difference = resumeTime.getTime() - pauseTime.getTime(); // This will give difference in milliseconds
    var resultInMinute = Math.round(difference / 60000);

    alert(resultInMinute);
Run Code Online (Sandbox Code Playgroud)

目前我无法计算包括时间在内的两个日期之间的差异。我收到错误 undefined is not a function resumeTime.getTime() ???

谢谢你的帮助。

Der*_*會功夫 5

getTimeStamp()不返回时间戳(这样具有讽刺意味),而是返回以下格式的字符串:"1/20/2014 19:18:28"

这就是您如何获得以毫秒为单位的时间戳:Date.now(),甚至Date().toString()(以文本表示的时间)。

您应该存储它,以便以后可以通过执行以下操作来重用它:

new Date(yourTimestamp);  //this returns the original Date object

(newTimestamp - oldTimestamp)/1000/60   //returns difference in minute
Run Code Online (Sandbox Code Playgroud)