Date object is used as part of calculating the date/time just before DST adjustments occur. I needed a solution with this behavior to properly adjust UTC date/time for previous and future dates intended for display to users. Feel free to adapt the code for your own uses.
Using the Code
The DST determination is split between two functions. The
DisplayDstSwitchDates() function locates the initial date/time for each month before a timezone change occurs. This method internally calls the
FindDstSwitchDate() method, which in turn determines the exact minute before a timezone change occurs.
To elaborate more on the code, let's first take a look at the
DisplayDstSwithDates() function. This function is very simple. Its only purpose is to get the date/time from 12 consecutive months and compare the timezone offset month to month. When the timezone changes, the month prior to the current date/time checked is captured. Typically, there are two times the timezone will change if the code is running on a browser running in a geographical location where DST is observed. The
for loop completes once the month counter (variable
i) reaches 12. With the current year and the two month numbers captured, the
FindDstSwitchDate() function is called.
FindDstSwitchDate() function may appear busy, but it is actually very simple. The first part of the function starts checking the timezone offset day by day, beginning with the month and year supplied as function parameters. Once the timezone offset changes, the day prior to the timezone offset change is captured. The rest of the function counts minute by minute, beginning with the day captured, until the timezone offset changes. The minute prior to the actual date/time that the timezone offset changes is captured. Using the captured day and number of minutes, the function assembles a string to represent the date/time that is one minute prior to when a timezone offset change occurs. This function is called twice for locations where DST is observed. One date represents a minute before when you turn the clock back an hour, and the other date represents a minute before when you move the clock ahead by an hour.
If you would like to learn more about DST and see the applicable DST rules for countries around the world, please have a look here: time and date.com DST info.
Points of Interest
- v1.0: 02-14-2010: Initial post.
- v1.1: 02-14-2010: Added additional explanations for the code.
- v1.2: 02-18-2010: Added a conditional to add 1900 to the year to accommodate Firefox, Chrome, and perhaps other browsers.