Reputation: 6766
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.
Upvotes: 0
Views: 136
Reputation: 270768
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.
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.
Upvotes: 1