简体   繁体   中英

how DateTime and TimeZoneInfo classes handles the daylight saving?

I am trying to understand how .net does handle daylight saving. When I invoke IsDaylightSavingTime method and pass the date instance it returns true for today's date. If I invoke DateTime's IsDaylightSavingTime method on same date instace, it returns me false.

Why do I get different result for the same date instance?

public static void Main()
{
    var zone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
    
    var utcNow = DateTime.UtcNow;
    var pacificNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, zone);
    
    Console.WriteLine(zone.IsDaylightSavingTime(pacificNow)); // Prints True
    Console.WriteLine(pacificNow.IsDaylightSavingTime()); // Prints False
}

here is the link for fiddle.

The first line prints True because it is printing whether it is in daylight saving time in Pacific Time. Pacific Time changes to Standard Time on November 1 2020, and today is September 21, so it is daylight saving right now.

The second line prints False because it is not daylight saving in whatever timezone that your computer is in. This is because for DateTime s with a kind of Local or Unspecified , DateTime.IsDaylightSavingTime uses your computer's system timezone to determine its result:

This method determines whether the current DateTime value falls within the daylight saving time range of the local time zone, which is returned by the TimeZoneInfo.Local property.

TimeZoneInfo.Local :

The local time zone is the time zone on the computer where the code is executing.

The timezone isn't actually part of a DateTime , so pacificNow.IsDaylightSavingTime() has no idea that you want it to use Pacific 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