Home > Article > Web Front-end > How to Determine if Daylight Saving Time Is Currently in Effect in JavaScript?
Determining Daylight Saving Time (DST) Status
In JavaScript, calculating time differences accurately can be affected by DST, which adjusts local time by an hour. To handle this, it's essential to determine if DST is in effect.
Checking DST Status
The Date object provides a solution through getTimezoneOffset, which returns the difference between local time and UTC in minutes. However, note that getTimezoneOffset returns positive values for time zones west of UTC (e.g., Los Angeles) and negative values for those east of UTC (e.g., Sydney).
To account for this, the following code snippet can be employed:
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(); };
The stdTimezoneOffset function returns the greater offset value between January and July, effectively representing the standard time offset. The isDstObserved function then compares the current offset with this standard offset. If the current offset is less, it indicates DST is in use.
Example Usage
var today = new Date(); if (today.isDstObserved()) { alert("Daylight saving time!"); }
Note: DST start and end dates vary by region, so it's recommended to consult local sources for precise information.
The above is the detailed content of How to Determine if Daylight Saving Time Is Currently in Effect in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!