Last updated: Mar 6, 2024
Reading timeยท2 min
To check if DST (Daylight Saving time) is in effect:
getTimezoneOffset()
method to get the timezone offset for the 2
dates.function hasDST(date = new Date()) { const january = new Date( date.getFullYear(), 0, 1, ).getTimezoneOffset(); const july = new Date( date.getFullYear(), 6, 1, ).getTimezoneOffset(); return Math.max(january, july) !== date.getTimezoneOffset(); } // ๐๏ธ 1st of February 2022 console.log(hasDST(new Date(2022, 1, 1))); // ๐๏ธ false // ๐๏ธ 1st of September 2022 console.log(hasDST(new Date(2022, 8, 1))); // ๐๏ธ true
We created a reusable function that takes a Date
object as a parameter and
returns true
if DST (Daylight Saving Time) is in effect and false
otherwise.
We created 2 Date
objects - 1 in January
and the other 1 in July
.
The 3 parameters we passed to the Date() constructor are:
year
The getTimezoneOffset() method returns the difference, in minutes, between a date (evaluated in UTC) and the same date evaluated in the visitor's local time zone.
For an area where DST is observed, the offset the getTimezoneOffset
method
returns for January
will be different from the one returned for July
.
getTimezoneOffset
method returns a greater value during Standard Time than during Daylight Saving Time.The Math.max()
function takes two or more comma-separated numbers and returns
the max value.
console.log(Math.max(3, 5, 8)); // ๐๏ธ 8 console.log(Math.max(-5, 10, 3)); // ๐๏ธ 10
Therefore, the Math.max()
function will return the value that is during
Standard time.
The last step is to compare the value during Standard Time to the output from
calling the getTimezoneOffset
method on the passed-in date.
If the two values are equal, then the date matches the standard offset and Daylight Saving time is not observed.
You can learn more about the related topics by checking out the following tutorials: