【问题标题】:How do you get the Unix timestamp for the end of today in Javascript?你如何在 Javascript 中获得今天结束的 Unix 时间戳?
【发布时间】:2020-07-30 06:10:03
【问题描述】:

我想获取今天的结束 Unix 时间戳。

使用它获取今天的开始时间戳,但我想要今天的结束时间戳

var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;

【问题讨论】:

  • var endTimestamp = 时间戳 + 24 * 60 * 60 - 1;
  • 谢谢你,Karan,它正在工作
  • 如果“一天结束”是 24:00,则 new Date().setHours(24,0,0,0) 给出毫秒数。如果需要秒数,除以 1,000 并截断小数部分:new Date().setHours(24,0,0,0)/1000|0。如果“一天结束”是午夜前 1 秒,则使用 setHours(23,59,59,0)
  • 顺便说一句,一天的开始只是new Date().setHours(0,0,0,0)/1000|0。 :-)

标签: javascript date unix-timestamp


【解决方案1】:

864e5 是一天中的毫秒数(24 * 60 * 60 * 1000),now % 864e5 是日期的时间部分,以毫秒为单位:

var now = new Date
var startOfDay = new Date(now - now % 864e5)
var endOfDay   = new Date(now - now % 864e5 + 864e5 - 1)

console.log(now)
console.log(startOfDay)
console.log(endOfDay)

【讨论】:

    【解决方案2】:
    1. 您可以使用.valueOf() 方法来获取日期的毫秒时间戳,而不是date / 1000
    2. 要结束一天,只需取第二天的日期并减少 1 毫秒

    var now = new Date();
    var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    // take next day date and reduce for one millisecond
    var endOfDay = new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1) - 1);
    
    console.log({
      startOfDay,
      endOfDay,
      startOfDayTimestamp: startOfDay.valueOf(),
      endOfDayTimestamp: endOfDay.valueOf()
    })

    【讨论】:

      【解决方案3】:

      首先,获取今天的时间戳:

      var now = new Date();
      

      那就明天开始吧:

      var startOfTomorrow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDay() + 1);
      

      今天你已经结束了:

      var timestampOfEndOfDay = (startOfTomorrow - 1); 
      

      查看结果:

      console.log("End of the Day", new Date(timestampOfEndOfDay) );
      

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
      猜你喜欢
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 2015-03-29
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多