简体   繁体   中英

C# Handling Daylight Saving in Time Conversion

I have a date string 2020-11-26T14:24:29-08:00 which is passed to the backend ASP NET MVC application.

I am parsing the date/time string using the below code:

    DateTime dateTime = DateTimeOffset.ParseExact("2020-11-26T14:24:29-08:00", 
                                                  "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
                                                  CultureInfo.InvariantCulture).DateTime;

This code is giving me time which is 1 hour less than the actual time. This is because of Daylight Savings.

Now, I want to know if daylight saving is active in the timezone or not. So I wrote the below code:

var offset = DateTimeOffset.ParseExact("2020-11-26T14:24:29-08:00", 
                                       "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz", 
                                       CultureInfo.InvariantCulture);

TimeZoneInfo zone = null;
foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
{
    if(zone.BaseUtcOffset == offset.Offset)
            zone = z;                        // this runs multiple times   
}

The above code if condition is hitting multiple times with the following zones satisfying condition.

  • Yukon Standard Time
  • Pacific Standard Time (Mexico)
  • UTC-08
  • Pacific Standard Time

So, I further narrowed down the code

var offset = DateTimeOffset.ParseExact("2020-11-26T14:24:29-08:00", 
                                       "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz", 
                                       CultureInfo.InvariantCulture);

TimeZoneInfo zone = null;
foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
{
    if(zone.BaseUtcOffset == offset.Offset && zone.SupportsDaylightSavingTime)   // added second condition
            zone = z;                        // this runs multiple times   
}

This time I got three:

  • Yukon Standard Time
  • Pacific Standard Time (Mexico)
  • Pacific Standard Time

Is it possible to get the exact timezone? (I know this user is in Pacific Standard Time ) Or is it okay to use any (first one) and add one hour to time to get the correct time?

If that datetime string is all you're able to use, I suspect you have to hope the offset they've given you is in line with their time zones daylight savings time (and so could be different for the same location).

I think more information might be needed before a useful answer can be given. Where is this value coming from, what use is the daylight savings time?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM