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

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
2 min

banner

# 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.
index.js
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

check if daylight saving time is in effect

The code for this article is available on GitHub

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:

  1. The year
  2. A zero-based value for the month (January = 0, February = 1, etc)
  3. 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 from 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.

index.js
console.log(Math.max(3, 5, 8)); // ๐Ÿ‘‰๏ธ 8 console.log(Math.max(-5, 10, 3)); // ๐Ÿ‘‰๏ธ 10

using math max function

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev