DST Detection and Offset Calculation in JavaScript
The given code calculates the time difference between two dates, breaking it down into years, days, hours, minutes, and seconds. However, Daylight Saving Time (DST) may cause discrepancies. This article delves into the mechanism for determining whether DST is in effect and calculating its offset.
Checking for DST
The key lies in the getTimezoneOffset() method. It returns a larger value during Standard Time compared to DST. By determining the expected offset during Standard Time, the code compares it with the offset for the given date. If the offset is smaller, it indicates DST.
getTimezoneOffset Considerations
Note that getTimezoneOffset() returns positive values for time zones west of UTC, which are typically represented as negative hours (e.g., Los Angeles: UTC–8h in Standard Time). In contrast, it returns negative values for the Eastern Hemisphere (e.g., Sydney: UTC+10h in winter).
Code Example
To extend Date with DST functionality:
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(); }
Usage:
var today = new Date(); if (today.isDstObserved()) { alert ("Daylight saving time!"); }
By incorporating this functionality, your code can accurately calculate time differences, even during DST transitions.
위 내용은 일광 절약 시간이 적용됩니까? DST 오프셋 감지 및 계산을 위한 JavaScript 접근 방식.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!