【问题标题】:Find next occurrence of a time in a non-local timezone (in this case, PST)在非本地时区(在本例中为 PST)中查找下一次出现的时间
【发布时间】:2021-09-25 11:45:05
【问题描述】:

无论客户的时区如何,我都想知道特定 PST 时间的下一次出现有多远。

如果时间是 UTC,这将是微不足道的,但我不知道如何在 PST 中做到这一点,记住要遵守夏令时。

例如。太平洋标准时间下午 4 点将是世界标准时间晚上 11 点,因为现在是夏天。

我宁愿不必手动输入夏令时的日期。

如果没有库就无法使用,我很乐意使用。

// returns the number of milliseconds from the current time until the specified time in PST.
function getTimeUntil (hour, minutes = 0, seconds = 0)
{
    // implementation needed
}

【问题讨论】:

  • 假设 PST 是美国太平洋标准时间,那么太平洋标准时间下午 4 点 (16:00) 始终是 00:00 UTC,因为 PST 有一个固定的偏移量:UTC -8。大多数(尽管不是全部)在冬季观察 PST 的地方在夏季观察 PDT(UTC -7)。在那些地方 16:00 PDT 是 23:00 UTC。

标签: javascript date timezone dst


【解决方案1】:

以下解释了为什么这可能与How to initialize a JavaScript Date to a particular time zone 重复。

PST(可能是美国太平洋标准时间)是具有固定偏移量的时区,UTC -8。遵守 PST 并实行夏令时的地方通常称其为太平洋夏令时 (PDT),即 UTC -7。

PST 也可能是皮特凯恩标准时间,这也是 UTC -8 并且在皮特凯恩岛全年观察到。将 PST 转换为 UTC 是通过增加 8 小时来实现的。

但是,您可能希望使用在冬季遵守美国 PST 和夏季遵守美国 PDT 的地方的时间和日期,例如洛杉矶。在这种情况下,您可以使用 Luxon 或 date.js 之类的库,它允许根据时间戳和指定的 IANA 代表位置(例如“America/Los_Angeles”)创建日期。如果是这种情况,请参阅上面的链接。

【讨论】:

  • 我不确定在太平洋标准时间的哪个地方不考虑夏令时,但我很确定在加拿大和美国是这样。
【解决方案2】:

我的实现:

// returns the formatted time from the current time until the specified time in PST.
function getTimeUntil (hour, minutes = 0, seconds = 0)
{
    let future = luxon.DateTime.now().setZone('America/Vancouver').set({
        hours: hour,
        minutes: minutes,
        seconds: seconds
    });
    let now = luxon.DateTime.now().setZone('America/Vancouver');
    if (future < now)
    {
        future = future.plus({ days:1 });
    }
    return future.diff(now, ["hours", "minutes", "seconds"]);
    // implementation needed
}

console.log(getTimeUntil(13, 0, 0).toObject());
&lt;script src="https://cdn.jsdelivr.net/npm/luxon@2.0.1/build/global/luxon.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 2019-07-03
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多