【问题标题】:How to check if there has been a time change between to UNIX timestamps如何检查到 UNIX 时间戳之间是否有时间变化
【发布时间】:2021-06-12 22:30:42
【问题描述】:

所以在我的本地时区(东部标准时间),本地时间增加了 1 小时,这意味着在 3 月 14 日凌晨 02:00 我们跳到了凌晨 03:00。

我的目标是通过比较两个具有相同 HH:MM:s 的 UNIX 时间戳,一个在发生时间更改之前和另一个之后,找到这两者之间发生了时间更改,如果所以它是什么。

我正在使用moment.js,但计算这两个日期相同的日期之间的差异将得到 0 小时差异。

    //Sat Mar 13 2021 16:00:00 GMT-0500 (Eastern Standard Time)
    const before = moment(1615669200000);

    //Sun Mar 14 2021 16:00:00 GMT-0400 (Eastern Daylight Time)
    const after = moment(1615752000000)

    const diff = before.diff(after, 'hours')

    // console.log(diff) will print 0, not 1

【问题讨论】:

  • 在美国,时间跳跃发生在凌晨 02:00,而不是凌晨 12:00,尽管我认为这对于这个问题并不重要。
  • 您使用的是时间戳还是其他格式?请分享更多详细信息,例如您正在使用的代码(给定的代码不使用时间戳)
  • isDST() 方法能解决问题吗?只需检查这两个时刻是否相同。
  • @AdarshMohan 他预计是 23 小时,因为 DST 更改时缺少一个小时。但 moment.js 会自动调整。
  • 如果您要比较两个时间戳,只需检查差异是否为 86400 的倍数。

标签: javascript time momentjs dst


【解决方案1】:

你不需要 Moment (由于它的 current status,你应该考虑不使用它。)

要了解两个时间戳之间的本地时间是否存在转换,您需要在这些时间戳之间进行搜索,以比较它们与 UTC 的本地偏移量。

function localTimeZoneHasTransitionBetween(t1, t2) {

  if (typeof(t1) !== 'number' || typeof(t2) !== 'number')
    throw "Timestamps must be numbers.";

  if (t1 > t2)
    throw "Timestamps must be in sequence.";

  // Get the local offset of the first timestamp.
  const o = new Date(t1).getTimezoneOffset();

  // Check if it's different from the second timestamp.
  if (new Date(t2).getTimezoneOffset() !== o) {
    // It's different, so there was obviously a transition.
    return true;
  }
  
  // Search linearly between the two timestamps.
  let t = t1;
  while (t < t2)
  {
    if (new Date(t).getTimezoneOffset() !== o) {
      // The timestamps have different local offsets,
      // thus a transition occured somewhere between them.
      return true;
    }
    
    // Advance a day.  Transitions are not likely to occur at smaller intervals.
    t += 24 * 60 * 60 * 1000;
  }

  // The offsets were always the same, so there was
  // no transition between them.
  return false;
}

// Example usage
console.log(localTimeZoneHasTransitionBetween(1615669200000, 1615752000000));

上面执行线性搜索。可以通过使用二分搜索来提高其性能。

另外,如果您只想知道两个时间戳是否有不同的偏移量,您可以在每个时间戳上调用new Date(timestamp).getTimezoneOffset() 并进行比较。当然,这不会告诉你它们之间是什么

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2013-03-23
    相关资源
    最近更新 更多