C# DateTime.Parse(String) 在不同的系统中返回不同的值

标签 c# datetime

今天,我观察到 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/

相关文章:

java - Joda时间(Java): Hijri to Gregorian conversion inaccurate?

c# - AutoFixture 设置夹具的声明方式背后的原则是什么?

c# - 如何循环 SQL 参数列表和 WHERE 子句?或者更有效地获得结果?

c# - 如何比较字符串和 bool 数组?

python - Pandas :从 read_sql 导入后将列解析/转换为日期

python - 在 panda DataFrame 列中获取上个月的第一个工作日

java - Joda Time 将 time zoneddatetime 转换为毫秒

c# - 使用 C# Windows 窗体应用程序(.NET Framework)进行 Windows Hello 验证?

c# - 对 Func<T> 进行泛型类型约束

按日期时间排序时,Mysql 查询太慢