tags:

views:

139

answers:

3

I want to compute the time 4 hours later during the DST transition, either into DST or out of it.

Currently doing this:

DateTime now = DateTime.now();
DateTime later = now.AddHours(4);
System.Console.WriteLine(now + " isDST " + now.IsDaylightSavingTime());
System.Console.WriteLine(later + " isDST " + later.IsDaylightSavingTime());

Provides:

11/1/2009 12:45:54 AM isDST True
11/1/2009 4:45:54 AM isDST False

What I want to see is:

11/1/2009 12:45:54 AM isDST True
11/1/2009 3:45:54 AM isDST False

The "best" way I've found to do this is to take a round trip through UTC like this:

DateTime now = DateTime.now();
DateTime later = now.ToUniversalTime().AddHours(4).ToLocalTime;
System.Console.WriteLine(now + " isDST " + now.IsDaylightSavingTime());
System.Console.WriteLine(later + " isDST " + later.IsDaylightSavingTime());

It seems I should be able to specify to AddHours() that the time returned should be elapsed time or display time. What am I missing?

+2  A: 

AddHours() deals with TimeSpans, which have no real concept of "display hours" or even timezones. It's essentially a whole number of ticks.

I think what you're doing is a pretty good way of handling it, if I understand your intent correctly.

womp
+2  A: 

I don't think you're missing anything. It sounds like DateTime could have a better documented or richer interface, but MSDN recommends using UTC exactly like you are.

There's a cute time difference between .NET and win32 in displaying times from a different daylight savings' rule than the present. .NET will display the time as it would have been displayed at that time, while win32 will always give it in terms of the current daylight savings flag.

wrang-wrang
+1  A: 

Yes, you should use UTC.

You're effectively talking about an instant in time 4 hours after the current instant. Not 4 hours of a particular local time, but 4 hours in "experienced" time, if you will. (Let's leave relativity out of it.) Imagine one person calls another and says, "I'll call you again in 4 hours" - both will know what that means, even if they're in completely different time zones with different DST transitions involved.

Instants are usually best expressed in UTC to avoid confusion - they're inherently "universal" rather than being in a particular time zone.

I'd avoid using local time until you need it:

DateTime localTimeInFourHours = DateTime.UtcNow.AddHours(4).ToLocalTime;

Or you could use DateTimeOffset if you want to end up with a "local time" in a time zone other than the one your computer is set to.

Jon Skeet