【问题标题】:How to get the timestamp of a specific previous/last time with Moment.js?如何使用 Moment.js 获取特定上一次/最后一次的时间戳?
【发布时间】:2021-09-29 21:03:18
【问题描述】:

下面给出了当前日期时间的时间戳:

来源

moment().utc().valueOf()

输出

1626964579209 // 2021-07-22T14:36:19Z

如何获取上一个/最后一个 07:00 AM (2021-07-22T07:00:00Z) 和 11:00 PM (2021-07-21T23:00:00Z) 的时间戳) 日期时间?

请注意,在这种情况下,最后/前一个 11:00 PM 时间戳来自前一天 (2021-07-21)。

我尝试过使用 Moment.js DurationsSubtract Time,但没有取得多大成功。

这里有一个 StackBlitz 可以玩:https://stackblitz.com/edit/typescript-ofcrjs

提前致谢!

【问题讨论】:

  • @dave 看来您找到了合适的解决方案!如果您将解决方案发布为答案,我将接受它作为此问题的解决方案。非常感谢您的帮助!

标签: javascript typescript date datetime momentjs


【解决方案1】:

你是这个意思吗?

moment('7:00 AM', 'h:mm A').subtract(1,'days').utc().valueOf();
moment('11:00 PM', 'hh:mm A').subtract(1,'days').utc().valueOf();

只需获取今天的时间并将天减去 1。

【讨论】:

  • 嗨@văn-vi 这是一个好的开始,但无论如何你都会减去一天。需要有一种方法来检查或设置这些时间是从当天开始还是从最后一天开始。看起来戴夫找到了一个合适的解决方案。无论如何,非常感谢您提供帮助!
【解决方案2】:

你可以的

const currentDateTime = moment().utc();
console.log('Current date-time timestamp:', currentDateTime.valueOf());
console.log('Current date-time string:', currentDateTime.format());

// If the current date-time string is 2021-07-22T14:36:19Z
// then the previous/last 07:00 AM string is 2021-07-22T07:00:00Z and the
// previous/last 11:00 PM string is 2021-07-21T23:00:00Z (previous day)
let last7amTimestamp = currentDateTime.clone().startOf('d').add(7, 'h'); // ???
if (last7amTimestamp.isAfter(currentDateTime)) {
  last7amTimestamp.subtract(1, 'd')
}
let last11pmTimestamp = currentDateTime.clone().startOf('d').add(23, 'h'); // ???
if (last11pmTimestamp.isAfter(currentDateTime)) {
  last11pmTimestamp.subtract(1, 'd')
}

console.log('Previous/last 07:00 AM timestamp:', last7amTimestamp);
console.log('Previous/last 11:00 PM timestamp:', last11pmTimestamp);

【讨论】:

    【解决方案3】:

    您可以测试当前的 UTC 时间,如果它在所需时间之后,只需将 UTC 时间设置为时间。如果是之前,请将其设置为前一天的小时,即小时 - 24。

    例如给定提供的日期或在没有 moment.js 的情况下默认为当前日期的通用函数是:

    // Get the previous hour UTC given a Date
    // Default date is current date
    function previousUTCHour(h, d = new Date()) {
      // Copy d so don't affect original
      d = new Date(+d);
      return d.setUTCHours(d.getUTCHours() < h ? h - 24 : h, 0, 0, 0);
    }
    
    // Example
    let d = new Date();
    console.log('Currently : ' + d.toISOString());
    [1, 7, 11, 18, 23].forEach(
      h => console.log('Previous ' + (''+h).padStart(2, '0') +
           ' ' + new Date(previousUTCHour(h)).toISOString())
    );

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 2014-06-18
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      相关资源
      最近更新 更多