在几分钟内比较两个时间戳JS

时间:2014-01-21 01:15:10

标签: 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())));
}

并在此处保存暂停时间:

localStorage["TmpPause"] = getTimeStamp();

比读完一段时间并比较:

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);

目前我无法计算包括时间在内的2个日期之间的差异。我得到的错误未定义不是函数resumeTime.getTime()???

感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以使用Date()的getTime方法。 这有用吗?:

$variable1 = (new Date()).getTime();
$variable2 = (new Date()).getTime();

$diff =  $variable2 - $variable1;

答案 2 :(得分:1)

日期对象的内部时间值是自1970-01-01T00:00:00Z以来的毫秒数。您可以直接比较两个日期,因为它们通常被强制转换为数字或字符串,例如

var d1 = new Date(2014,0,20,12,30,0); // 2014-01-20 12:30:00
var d2 = new Date(2014,0,21,02,30,0); // 2014-01-21 02:30:00

// Difference between d2 and d1 in milliseconds (50400000)
var msDiff = d2 - d1;

// Convert ms to decimal minutes (840)
var minutesDiff = msDiff/60000;

// Convert ms to mintues and seconds (840:0)
var mDiff = (msDiff/60000) | 0;
var sDiff = Math.round((msDiff % 60000) / 1000); 
console.log(mDiff + ':' + sDiff);

广泛支持时间值,因为它们也可用于创建日期:

var date = new Date(timevalue);

它们是交换代表特定时刻的价值观的常用方式。

答案 3 :(得分:0)

getTimeStamp()会返回字符串(谈论错误的命名......)。

您无法在该字符串上调用不存在的函数:resumeTime.getTime()

为什么不简单地存储实时时间戳?