简体   繁体   English

DateTime 和 TimeZoneInfo 类如何处理夏令时?

[英]how DateTime and TimeZoneInfo classes handles the daylight saving?

I am trying to understand how .net does handle daylight saving.我想了解 .net 如何处理夏令时。 When I invoke IsDaylightSavingTime method and pass the date instance it returns true for today's date.当我调用IsDaylightSavingTime方法并传递日期实例时,它为今天的日期返回 true。 If I invoke DateTime's IsDaylightSavingTime method on same date instace, it returns me false.如果我在同一日期实例上调用 DateTime 的IsDaylightSavingTime方法,它会返回 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.第一行打印True是因为它打印的是太平洋时间是否处于夏令时。 Pacific Time changes to Standard Time on November 1 2020, and today is September 21, so it is daylight saving right now.太平洋时间在 2020 年 11 月 1 日更改为标准时间,今天是 9 月 21 日,所以现在是夏令时。

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:第二行打印False因为它不是您计算机所在时区的夏令时。这是因为对于具有LocalUnspecified类型的DateTimeDateTime.IsDaylightSavingTime使用您计算机的系统时区来确定其结果:

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.此方法确定当前 DateTime 值是否在本地时区的夏令时范围内,该范围由TimeZoneInfo.Local属性返回。

TimeZoneInfo.Local :时区信息. 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.时区实际上不是DateTime的一部分,因此pacificNow.IsDaylightSavingTime()不知道您希望它使用太平洋时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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