【问题标题】:Getting difference in seconds from two dates in JavaScript从 JavaScript 中的两个日期获取以秒为单位的差异
【发布时间】:2012-04-03 15:08:39
【问题描述】:

我使用 Date() 将日期存储在 MongoDB 中,MongoDB 使用 UTC 它是日期类型,并且字符串看起来像 Mon, 02 Apr 2012 20:16:31 GMT

我想获取此时间与当前时间(以 UTC 为单位)之间的时间差,以总秒为单位。

我试过这个:

now = new Date();
current_date = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
end_date = obj.end_date (Mon, 02 Apr 2012 20:16:35 GMT);
d = new Date(end_date - current_date);
console.log(d.getSeconds());

这会显示22 几秒钟,这显然是不对的。

它似乎也过于复杂。也许 MongoDB 中有更好的方法或 JavaScript 中有正确的方法来做到这一点?

任何建议都会很棒 - 谢谢!

【问题讨论】:

    标签: javascript mongodb


    【解决方案1】:

    您可以在 Date 对象上使用 getTime() 来获取以毫秒为单位的差异,然后将差异除以 1000;

    例如

    now = new Date();
    current_date = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    end_date = obj.end_date (Mon, 02 Apr 2012 20:16:35 GMT);
    var millisDiff = end_date.getTime() -  current_date.getTime();
    console.log(millisDiff / 1000);
    

    【讨论】:

      【解决方案2】:

      (end_date.getTime() - current_date.getTime()) / 1000

      getSeconds 将只返回秒,而不是分钟、小时等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-27
        • 2012-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-20
        • 2012-09-13
        相关资源
        最近更新 更多