如何检查 UNIX 时间戳之间是否有时间变化

How to check if there has been a time change between to UNIX timestamps

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

我的目标是通过比较两个具有相同 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

您不需要为此使用 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() 并比较它们。当然,这不会告诉你他们之间是什么。