【问题标题】:Compare two Time stamps in minutes JS以分钟为单位比较两个时间戳 JS
【发布时间】:2014-01-21 01:15:10
【问题描述】:

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

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 个日期之间的差异。我收到错误 undefined is not a function resumeTime.getTime() ???

感谢您的帮助。

【问题讨论】:

  • “时间戳”的格式不符合任何常见的编程用途。最好使用标准化的东西(例如 ISO 8601)。

标签: javascript time


【解决方案1】:

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

【讨论】:

  • 完美,这是最短的解决方案和工作 - 谢谢
  • 没有讽刺意味,通常timestamps 是字符串。 “1/20/2014 19:18:28”时间戳。 :-)
【解决方案2】:

Date 对象有一个内部 timevalue,它是自 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】:

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

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

    【讨论】:

    • javascript中没有日期“类”。
    • @RobG 怎么没有? new Date() 在 Javascript 中非常常见。试试看。
    • javascript中没有类,有类语法,但javascript只是由具有原型继承的函数(构造函数)创建的对象。 :-)
    【解决方案4】:

    getTimeStamp() 返回一个字符串(谈论不好的命名......)。

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

    为什么不简单地存储真正的时间戳?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 2021-01-04
    • 2021-05-12
    • 2014-01-03
    • 2011-07-18
    • 2014-07-11
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多