Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception calling when TimeZoneInfo.ConvertTimeToUtc for certain DateTime values

Tags:

When I run the code for this specific value of dt, an exception is thrown when I call the ConvertTimeToUtc Method. My local Machine timeZoneId is "GMT Standard Time"

var tzi = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); var dt = new DateTime(1995, 4, 2, 2, 55, 0); var t = TimeZoneInfo.ConvertTimeToUtc(dt, tzi); 

The exception is:

System.ArgumentException was unhandled Message="The supplied DateTime represents an invalid time.  For example, when the clock is adjusted forward, any time in the period that is skipped is invalid.\r\nParameter  
like image 811
B4ndt Avatar asked Mar 10 '10 11:03

B4ndt


2 Answers

Yes, that's absolutely right. 2:55am didn't exist in Central Standard Time on April 4th 1995, as the wall clock skipped from 2am to 3am due to daylight saving transitions. The exception seems reasonably clear about this. (The use of "standard" is somewhat tricky here; it would make more sense to call it "Central Time" which would include "Central Standard Time" and "Central Daylight Time" but that's a different matter. Heck, I'd prefer Olson identifiers myself...)

At other times, a local time may be ambiguous - if the clock goes back an hour (or more!) then a local time may occur twice.

The question is: how do you want your code to behave in this situation?

It's somewhat unfortunate that the exception is just ArgumentException - in Noda Time we're going to have an exception for this exact case, so that it's easier to spot and catch. (We'll also have something like IsAmbiguous and IsSkipped so you can check without catching an exception.)

But the basic message is that this isn't a bug in the BCL - it's deliberate.

like image 64
Jon Skeet Avatar answered Oct 01 '22 01:10

Jon Skeet


One can test whether the time in question is invalid using

TimeZoneInfo.IsInvalidTime 

or if it is ambiguous using

TimeZoneInfo.IsAmbiguousTime 

If it is ambiguous, an array of times that could apply can be retrieved from

TimeZoneInfo GetAmbiguousTimeOffsets 

In the case of an interactive application, the user can be prompted for clarification.

The BCL team wrote a good blog about the topic

https://docs.microsoft.com/en-au/archive/blogs/bclteam/system-timezoneinfo-working-with-ambiguous-and-invalid-points-in-time-josh-free

like image 25
Eric J. Avatar answered Oct 01 '22 03:10

Eric J.