KV Sites on Facebook

DST problem and solution

Kae Verens ~ Friday 26th October, 2012

Daylight Savings Time was invented in the 19th century by George Vernon Hudson, and is a terrible idea. It causes missed appointments, traffic jams, and fatal accidents.

Unfortunately, we're stuck with it for the forseeable future.

In this post, I'm going to describe a little problem to do with one single hour in every year, which is a huge pain in my ...head.

As programmers, most of the year when writing programs that use time, we consider the task of counting time to be a simple problem, and then suddenly, in late October, we get people complaining about weird things happening in their programs.

When writing a calender program, it is customary to record items in a database with the date in this format: yyyy-mm-dd hh:mm:ss. This makes it very easy to check what items belong to what day, as we can just run a database query such as select * from calendar where item_date like "2012-10-28%".

Adding a day onto that date, though, is not straight forward. What is Feb 28th plus one day? Depends on the year. The way we figure the date out, is the use a function like time(), which returns a large number - the number of seconds that have passed since the beginning of 1970. We then add on one day (60 seconds * 60 minutes * 24 hours) and then convert to a date using the date() function.

The problem is... this works for every single day of the year except that one day where the clocks go back. When you add 24 hours on to Sunday the 28th of October 2012, it is still Sunday the 28th of October 2012. And so when we run the database query as above, to retrieve the next day's items, we are actually retrieving Sunday's items all over again.

There are some other problems to do with DST: most countries handle it differently or don't handle it at all (link), and even when sticking to just one country (Ireland), there is no exact date on which it happens. Instead, it happens on the 4th Sunday of October.

Solution: There is no simple whatIsTheFourthSundayOfOctober() function, so instead, what I do is to add on 24*60*60 seconds in all cases, but if the month number is 10 and the tens digit of the day number is greater than 1, then add on an extra 60*60 seconds. In most calendering apps, this will get around the problem perfectly.