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

时间:2021-03-15 16:15:42

标签: javascript time momentjs dst

因此,在我的本地时区(东部标准时间)中,本地时间增加了 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

1 个答案:

答案 0 :(得分:2)

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