c# - 让 C# 为已解析的 ISO 8601 字符串正确设置 Kind 属性

标签 c# datetime iso

我很难理解为什么要解析 ISO 8601 DateTime 的 Parse 方法解析的格式化字符串未正确设置新 DateTime 对象的 Kind 属性。我已经查看了帖子 How to create a .NET DateTime from ISO 8601 format结合 ISO 文档,Parse 方法似乎应该能够设置 Kind 值,但事实并非如此。

例子:

Console.Write(System.DateTime.Parse("2018-11-17T01:00:00").Kind);

返回:未指定

然而,根据 ISO 标准,这是一种有效格式,表明该值是本地时间。

Time Zone Section

Time zones in ISO 8601 are represented as local time (with the location unspecified), as UTC, or as an offset from UTC. If no UTC relation information is given with a time representation, the time is assumed to be in local time.

Coordinated Universal Time (UTC)

If the time is in UTC, add a Z directly after the time without a space. Z is the zone designator for the zero UTC offset

更奇怪的是,在字符串中添加 Z 会将 Kind 属性设置为 Local。

为了获得为 UTC 字符串正确设置的 Kind 值,Parse 方法中需要 RoundtripKind 的 DateTimeStyle。但是,如果从字符串中删除 Z,Kind 将再次设置为 Unspecified。

这是 DateTime 类的问题吗?

Microsoft 没有遵循 ISO 标准吗?

还是我不了解 ISO 标准?

最佳答案

要解析 ISO 8601 字符串并适当设置 DateTimeKind,您可以使用 DateTimeStyles.RoundtripKindthe o standard format specifier或包含 the K custom format specifier 的自定义字符串.

例如:

DateTime dt = DateTime.ParseExact(yourISO8601String, "yyyy-MM-dd'T'HH:mm:ss.FFFK",
                                CultureInfo.InvariantCulture, DateTimeStyles.RountripKind);

DateTimeStyles.RoundtripKind 提供以下行为:

  • 如果传入值没有提供时区偏移量,则生成的 DateTime 将具有 DateTimeKind.Unspecified
  • 如果传入值的时区偏移量为 Z,则生成的 DateTime 将具有 DateTimeKind.Utc
  • 如果传入值有数字时区偏移,例如 -07:00+01:00,甚至 +00:00,生成的 DateTime 将具有 DateTimeKind.Local,该值将从提供的时区偏移量转换为本地时区。

虽然这适用于许多情况,但第三个项目符号的转换行为通常是不希望的,因此在大多数情况下,最好解析为 DateTimeOffset 而不是 DateTime.

关于c# - 让 C# 为已解析的 ISO 8601 字符串正确设置 Kind 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53567018/

相关文章:

java - 刻录到磁盘后无法加载字体

java - 如果我遵循 ISO/IEC 5218,我的 'Person' 类应该有 int sex 吗?

c# - 使用 LINQ 查找给定素数数组的数字的除数数

c# - C# 中的全局变量

java - JodaTime 从期间获取值

mysql - 从数据库的日期时间列中减去 1 个月

c - 如何使用序号日和 1 月 1 日的星期几计算 ISO 工作日?

c# - 是否可以在 MatLab 中使用 .NET 应用程序?

c# - 如何将通用字典转换为其已知类型?

Mysql:计算访问频率