Exception calling when TimeZoneInfo.ConvertTimeToUtc for certain DateTime values

前端 未结 2 919

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\"

相关标签:
2条回答
  • 2020-12-29 23:14

    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

    0 讨论(0)
  • 2020-12-29 23:17

    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.

    0 讨论(0)
提交回复
热议问题