且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查DST(夏令时)是否有效以及它是否是偏移量?

更新时间:2022-05-06 19:35:45

此代码使用 getTimezoneOffset 返回更大值的事实在标准时间与夏令时(DST)期间。因此,它确定标准时间内的预期输出,并比较给定日期的输出是否相同(标准)或更低(DST)。

This code uses the fact that getTimezoneOffset returns a greater value during Standard Time versus Daylight Saving Time (DST). Thus it determines the expected output during Standard Time, and it compares whether the output of the given date the same (Standard) or less (DST).

注意 getTimezoneOffset 返回区域 west 正分钟数UTC的/ em>,通常表示为小时(因为它们落后于UTC)。例如,洛杉矶 UTC-8h 标准, UTC-7h DST。 getTimezoneOffset 12月(冬季,标准时间)返回 480 (正480分钟),而不是 -480 。它返回东半球的数字(冬季悉尼的 -600 ,尽管这是领先( UTC + 10h )。

Note that getTimezoneOffset returns positive numbers of minutes for zones west of UTC, which are usually stated as negative hours (since they're "behind" UTC). For example, Los Angeles is UTC–8h Standard, UTC-7h DST. getTimezoneOffset returns 480 (positive 480 minutes) in December (winter, Standard Time), rather than -480. It returns negative numbers for the Eastern Hemisphere (such -600 for Sydney in winter, despite this being "ahead" (UTC+10h).

Date.prototype.stdTimezoneOffset = function () {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.isDstObserved = function () {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

var today = new Date();
if (today.isDstObserved()) { 
    alert ("Daylight saving time!");
}