今天,我观察到 DateTime.Parse(String)
方法在不同服务器上运行时的一些奇怪行为。这可以在不同的在线 C# 编译器中观察到。
我以 yyyy-MM-ddTHH:mm:ssZ
格式输入。示例:让我们使用转换为刻度的 2020-02-12T16:57:36Z
是: 637171234560000000
(使用 https://tickstodatetime.azurewebsites.net/ 转换)
这是我用于测试此行为的代码:
DateTime parsedDateTime = DateTime.Parse("2020-02-12T16:57:36Z");
Console.WriteLine(parsedDateTime + " " + parsedDateTime.Kind.ToString() + " " + parsedDateTime.Ticks);
在 https://dotnetfiddle.net/akuyiI 上,它返回
02/12/2020 16:57:36 Local 637171234560000000
。在 https://rextester.com/XWH12209 上,它返回
12.02.2020 17:57:36 Local 637171270560000000
我知道 DateTime 被解析为本地时区并以本地时间显示,但为什么系统之间的滴答数也不同?
最佳答案
yyyy-MM-ddTHH:mm:ssZ
中的一个字符串格式表示a date in UTC .
它被正确解析,但不幸的是,结果 DateTime
值(value) is DatetimeKind.Local
,其值会根据计算机的时区进行相应调整。
正如 DateTime
source code file 开头的评论中所述,
Starting from V2.0, DateTime also stored some context about its time zone in the form of a 3-state value representing Unspecified, Utc or Local. This is stored in the two top bits of the 64-bit numeric value with the remainder of the bits storing the tick count. This information is only used during time zone conversions and is not part of the identity of the DateTime. Thus, operations like Compare and Equals ignore this state. This is to stay compatible with earlier behavior and performance characteristics and to avoid forcing people into dealing with the effects of daylight savings. Note, that this has little effect on how the DateTime works except in a context where its specific time zone is needed, such as during conversions and some parsing and formatting cases.
因此,
Ticks
DatetimeKind.Local
的属性日期相对于本地 12:00:00 midnight, January 1, 0001
, 不是 UTC 12:00:00 midnight, January 1, 0001
.这记录在 remarks for the
Ticks
property 中.这也意味着通过这种
DateTime.Parse
获得的两个日期实例在不同时区的不同服务器上,即使它们来自描述相同 UTC 日期的相同字符串,也会被比较为“不相等”。这是为了向后兼容。为了直接比较刻度,您需要convert两个日期都为
Kind.UTC
第一的。
关于C# DateTime.Parse(String) 在不同的系统中返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60205347/