Check if DST (Daylight Saving Time) is in Effect using JS


Borislav Hadzhiev

Last updated: Jan 22, 2022


Photo from Unsplash

Check if DST (Daylight Saving Time) is in Effect using JS #

To check if DST (Daylight Saving time) is in effect:

  1. Create 2 dates - 1 in January and 1 in July.
  2. Use the getTimezoneOffset() method to get the timezone offset for the 2 dates.
  3. Check if the greater of the two values is not equal to the offset for the original date.
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 the year, a zero-based value for the month (January = 0, February = 1, etc), and the day of the month (1 - 31).

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 to the one returned for July.

The 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 not equal, then Daylight Saving time is observed for the passed in date.

If the two values are equal, then the date matches the standard offset and Daylight Saving time is not observed.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.