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.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!