【问题标题】:How to get unix timestamp from tomorrow nodejs如何从明天的nodejs获取unix时间戳
【发布时间】:2019-04-19 20:21:41
【问题描述】:

我想从明天开始获取 Unix 时间戳(时间以秒为单位)。

我尝试了以下方法但没有成功:

var d = new Date();
d.setDate(d.getDay() - 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d/1000|0)

我将如何解决上述问题?

【问题讨论】:

  • 明天是今天 1,而不是减1。并且使用.getDate()而不是.getDay()
  • getDay() 以毫秒为单位返回当天的时间,所以 -1 或 +1 不会做任何事情 getDate() 会改变什么?
  • 不,getDay() 返回星期几。
  • 这应该可以按照问题描述var d = new Date(); d.setDate(d.getDate() + 1); d.setHours(0, 0, 0); d.setMilliseconds(0); console.log(d)

标签: javascript node.js date


【解决方案1】:

刚刚修改了你的代码,它工作正常

var d = new Date();
d.setDate(d.getDate() + 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d)
>> Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time)

希望这对你有用

【讨论】:

    【解决方案2】:

    应该这样做。

    直接从https://javascript.info/task/get-seconds-to-tomorrow复制

    function getSecondsToTomorrow() {
      let now = new Date();
    
      // tomorrow date
      let tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1);
    
      let diff = tomorrow - now; // difference in ms
      return Math.round(diff / 1000); // convert to seconds
    }
    
    console.log(getSecondsToTomorrow());

    【讨论】:

    • let toTomorrow = new Date().setHours(24,0,0,0) - Date.now()。 ;-) 如果您认为它是重复的,则应将其标记为重复,而不仅仅是将另一个答案复制到此处的答案中。
    • @RobG 不是重复的。这个答案来自一个完全不同的网站。
    【解决方案3】:

    你可以使用像moment js这样的第三方库,让你的生活更轻松

    momentjs

    【讨论】:

    • 说“使用库 X”不是答案。
    【解决方案4】:

    您可以使用 unix 时间戳并将 24*60*60*1000(与 86400000 相同)添加到当前时间的时间戳。然后你可以像这样将它传递给new Date()

    • 24 = 小时
    • 60 = 分钟
    • 60 = 秒
    • 1000 = 将结果转换为毫秒

    // Current timestamp
    const now = Date.now()
    
    // Get 24 hours from now
    const next = new Date(now + (24*60*60*1000))
    
    // Create tomorrow's date
    const t = new Date(next.getFullYear(), next.getMonth(), next.getDate())
    
    // Subtract the two and divide by 1000
    console.log(Math.round((t.getTime() - now) / 1000), 'seconds until tomorrow')

    【讨论】:

    • 这会在处理闰秒和夏时制时给出不正确的结果。
    猜你喜欢
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2019-06-10
    • 2018-07-11
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多