【问题标题】:Difference between hours using moment使用时刻的小时之间的差异
【发布时间】:2021-11-16 09:22:48
【问题描述】:

我知道这是互联网上的一个热门问题。但关键是我需要准确地做一些事情,由于我对日期的处理不是很熟悉,所以我需要问这个问题。

我的问题如下,我必须从时间戳定义某些操作。这些操作是在以下条件下采取的:

Prep - 在时间戳前大约一小时开始;

Run - 从时间戳开始;​​

Reset - 如果时间戳超过 15 分钟,则执行此操作;

请记住时间戳如下:

const timestamp = "2021-11-16T09:18:02+0000"

我有这样的想法:

const time = moment(timestamp).diff(moment(), "minutes")

但老实说,我不知道如何改进这一点。你能帮我吗? ????

【问题讨论】:

    标签: javascript node.js momentjs


    【解决方案1】:

    暂时不需要

    这应该可以帮助您入门

    const timestamp = "2021-11-16T09:18:02+0000"
    
    const d = new Date(timestamp)
    
    const prep = new Date(timestamp);
    prep.setHours(prep.getHours()-1);// Prep - starts about an hour before timestamp;
    
    // Run - starts right at timestamp;
    
    
    const resetTime = new Date(timestamp)
    // Reset - this action is taken if 15 minutes have passed after the timestamp;
    resetTime.setMinutes(resetTime.getMinutes()-15)
    
    console.log(d)
    console.log(prep)
    console.log(resetTime)
    
    console.log((d.getTime()-prep.getTime())/60000)

    【讨论】:

      【解决方案2】:

      这是我发现适合使用 momentjs 的解决方案

      const timestamp = "2021-11-16T09:18:02+0000"
      const reset = moment(timestamp).add(15, 'minutes').format('LT')
      const current = moment(timestamp).format('LT')
      const prev = moment(timestamp).subtract(1, 'hour').format('LT')
      
      console.log("Reset:",reset,"\nCurrent",current,"\nPrev",prev)
      <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

      退出时会发生什么

      reset 下午 3:03 current 下午 2:48 prev 下午 1:48

      更多关于momentjs

      【讨论】:

      • 无需时时刻刻包装。我已经更新了你的代码并做了一个 sn-p
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 2018-04-02
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      相关资源
      最近更新 更多