&. |

A software developer’s musings on software development

An Interesting Bug (Dates Are Weird)

Warning: I wrote this blog post in 2014. That is a long time ago, especially on the internet. My opinions may have changed since then. Technological progress may have made this information completely obsolete. Proceed with caution.

Not too long ago I was tasked with coding and designing a fairly simple calendar control. After I got it up and running and did some additional testing, I ran into an interesting problem: anytime I viewed a date in November, the calendar would look like this:

It only took me a minute to realize what I was doing wrong. Here is the jist of the algorithm (written in plain English so that hopefully non-geeks can understand it):

  1. Determine the first date that will be displayed on the calendar.
  2. Determine the last date that will be displayed on the calendar.
  3. Set DrawDate to FirstDate
  4. Do a loop while DrawDate <= LastDate
    1. If the current day of the week is the first day of the week, start a new row
    2. Draw DrawDate on the calendar
    3. Set DrawDate to DrawDate + 24 hours

Now when you look at the calendar, the most obvious thing is that there is a week with only one day. But the real problem is that November 2 is on the calendar twice.

What I forgot when initially coding this is that a day is not always twenty-four hours! If you observe daylight saving time, there is one day a year that is only 23 hours long (the day you “spring forward”), and one day that is 25 hours long (the day you “fall back”).

When I create a date, but don’t include time, it gets created with a time of 00:00:00 (midnight). So when I add 24 hours to November 2, 2014, I get 11pm on November 2, 2014, not midnight on November 3, 2014.

The fix is pretty simple: instead of adding 24 hours, add one day. The language already is smart enough to account for daylight saving time when you do this.