Share via


Answer of the month: IsDaylightSavingTime() or not?

Answer:

static DateTime GetAnswer()

{

   DateTime utc = new DateTime(2006, 10, 29, 8, 30,

                    0, DateTimeKind.Utc);

   return utc.ToLocalTime();

}

Explaination:

The main "trick" in this question is that the DateTime I want actually lands in the ambiguous hour when you fall back in Pacific time zone (PST). On first glance, most of you would probably created a DateTime like so:

static DateTime GetAnswer()

{

   DateTime wrong = new DateTime(2006, 10, 29, 1, 30, 0);

   return wrong;

}

However, when asking the Date Time whether it is in DaylightSavingTime or not, it will default to False. Because, by default, if a DateTime is ambiguous it will default to being the later repeated hour. i.e. the one not in Daylight Saving Time.

So, how can we get it? As you can see in the answer, the key to it is using UTC. UTC does not have daylight saving, it always map to exact point in time. The System.DateTime class has built in support to map Local time back to whatever UTC time you converted it from. That's why you can create a local ambiguous time that can tel whether you are in the first hour (in daylight saving) or the second hour (in standard time).

Did you guys already know this? If so, do you find this useful?

Comments

  • Anonymous
    August 11, 2006
    Yep, this is useful. I've never had to create such a DateTime myself on an actual project, but I did wonder how such "ambiguous" times were represented. Thanks for the tip.
  • Anonymous
    August 14, 2006
    Very interesting.  I just created a few months ago a 1.1 DateTime wrapper to do some time-zone support, so I know a bit about the subject, but I didn't know that about the 2.0 DateTime mapping  local -> UTC.