DateTimeKind 未指定,即使我设置了它

DateTimeKind is Unspecified Even Though I Set it

当我检查 optionDateDateTime 属性 的 DateTimeKind 值时,我看到未指定,即使我将 dt 的 DateTimeKind 设置为 UTC在下面的代码中。我希望 optionDate 有一个 DateTime,其中 DateTimeKind 属性 设置为 UTC。我哪里错了?

       var dt = new DateTime(Convert.ToInt32(optionDateInfo.dateTime.year),
            Convert.ToInt32(optionDateInfo.dateTime.month), Convert.ToInt32(optionDateInfo.dateTime.day),
            Convert.ToInt32(optionDateInfo.dateTime.hour), Convert.ToInt32(optionDateInfo.dateTime.minutes),
            0, DateTimeKind.Utc);

        var optionDate = new DateTimeOffset(dt);

使用 SpecifyKind

var myUtcZeroOffset = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc)

//If constructing a datetime offset to be not utc you can supply the offset instead
var myOffSetExplicitLocal = new DateTimeOffset(DateTime.Now, new TimeSpan(1, 0, 0));
var localDateTime = myOffSetExplicitLocal.DateTime;
var utcZeroOffSetDateTime = myOffSetExplicitLocal.UtcDateTime;

更糟糕的是,它是 Microsoft 的一个可批评的实现,因为根据 ISO 8601,通用协调时间不是时区而是一种符号,所以实际上 toUTC 作为一个概念是有缺陷的,因为 '2021-11 -02T10:16:25.12345+01:00' 在 UTC 格式和 UTC 零偏移量中完全有效,通常称为 Zulu 是 '2021-11-02T09:16:25.12345Z' 等价物,然后获取 datetimekind UTC 实际上就在协调时间围绕 GMT 纬度的零线,但使它协调的是 + 部分,在 +00:00 中可以缩写为 Z,因此做了很多工作来减轻固有冲突,并与构建服务器和云提供商一起使用 . Local 尤其可疑,所以我建议始终坚持使用 ISO 8601 字符串,除非您实际上需要在数据库中使用它们进行日期操作,在这种情况下要命名适当的字段,例如 DateTimeCreatedUtcZero 列,例如 只是我关于这个主题的五分理由,希望对您有所帮助。

记录在案:

DateTimeOffset.DateTime

The value of the DateTime.Kind property of the returned DateTime object is DateTimeKind.Unspecified.

请注意 DateTimeOffset 没有“种类”。它有日期、时间和偏移量。当您将类型为 UtcDateTime 传递给它时,它会将其偏移量设置为 0,并将其日期和时间设置为给定的 DateTime。此时,你的DateTimeKind就“丢”了。

偏移量为 0 并不一定意味着它的种类是 DateTimeKind.Utc。它可能是伦敦的当地时间,也可能是非洲某个地方的时间。所以它不能给你一个 DateTime with kind Utc 只是因为它的偏移量也是 0.

此外,DateTime能够表示3种事物已经是一个有问题的设计,如果DateTime 属性现在可以return 3种DateTime 取决于偏移量是否与本地时间匹配,是 UTC 还是其他时间,这更糟。

相反,它被设计为具有 3 个属性,可为您提供 DateTime 不同种类的属性。

  • DateTime 为您提供 DateTimeOffset 的日期和时间部分,类型为 Unspecified
  • LocalDateTimeDateTimeOffset 的日期和时间部分转换为当前时区,并为您提供类型为 Local.
  • DateTime
  • UtcDateTimeDateTimeOffset 的日期和时间部分转换为 UTC,并为您提供类型为 Utc.
  • DateTime

如果你想要 DateTime 类型 Utc,你应该使用最后一个。