【问题标题】:Why does format specifier "U" alter the value of DateTime?为什么格式说明符“U”会改变 DateTime 的值?
【发布时间】:2020-05-26 20:31:26
【问题描述】:

我在使用 DateTime 的“U”格式说明符时遇到了奇怪的行为,如以下通过测试所示:

DateTime tim = new DateTime(2020, 03, 29, 00, 59, 59);
  //test 1
Assert.Equal("2020-03-29 00:59:59Z", tim.ToString("u", CultureInfo.GetCultureInfo("en-GB")));
  //test 2
Assert.Equal("28 March 2020 23:59:59", tim.ToString("U", CultureInfo.GetCultureInfo("en-GB")));
  //test 3
Assert.Equal("Saturday, March 28, 2020 11:59:59 PM", tim.ToString("U", CultureInfo.GetCultureInfo("en-US")));
  //test 4
Assert.Equal("2020-03-29 00:59:59Z", timA.ToString("u", CultureInfo.GetCultureInfo("en-US")));

Test1 和 Test4 都生成包含日期和时间的预期字符串以显示给用户; 2020-03-29 00:59:59。但是,Test2 和 3 显示一个字符串,显示时间提前一小时; 2020 年 3 月 28 日 23:59:59。为什么格式说明符会改变值?

Microsoft Documentation 定义:

  • “u”(通用可排序日期/时间;标准格式字符串)UniversalSortableDateTimePattern,用于定义符合协调通用时间的 ISO 8601 标准的结果字符串。该属性是只读的。
  • “U”(通用完整日期/时间;标准格式字符串)FullDateTimePattern,用于定义结果字符串的整体格式。

为什么格式说明符会改变值?此外,为什么要改变一小时呢?

【问题讨论】:

    标签: c# datetime


    【解决方案1】:

    正如你在这里看到的The Universal Sortable ("u") Format Specifier

    不执行原始日期时间值的转换

    这里是The Universal Full ("U") Format Specifier

    值会自动转换为 UTC

    所以对于测试 2 和 3 断言 tim.ToUniversalTime()

    【讨论】:

    • 你是对的,将我的 DateTime 转换为 UTC 可以解决问题。但是,您没有解释为什么使用“U”格式说明符而不这样做会产生不正确的结果 - 即显示错误的时间。我在下面进行了详细说明,但会感谢您提供正确的答案。非常感谢。
    • 我没有解释,因为我不知道为什么。这个问题在我脑海中闪过。是的,我认为 API 不一致。
    【解决方案2】:

    “U”格式说明符只能用于 DateTimeKind.Utc 的日期时间。因此,通过更改我的 DateTime 构造函数,我能够生成具有预期结果的通过测试:

    DateTime tim = new DateTime(2020, 03, 29, 00, 59, 59, DateTimeKind.Utc);
    
    //test 1
    Assert.Equal("2020-03-29 00:59:59Z", tim.ToString("u", CultureInfo.GetCultureInfo("en-GB")));
    //test 2
    Assert.Equal("29 March 2020 00:59:59", tim.ToString("U", CultureInfo.GetCultureInfo("en-GB")));
    //test 3
    Assert.Equal("Sunday, March 29, 2020 12:59:59 AM", tim.ToString("U", CultureInfo.GetCultureInfo("en-US")));
    //test 4
    Assert.Equal("2020-03-29 00:59:59Z", tim.ToString("u", CultureInfo.GetCultureInfo("en-US")));
    

    我会将此作为错误报告给 Microsoft,因为对使用带有 不是 UTC 的日期时间的“U”(或“u”)格式说明符的合理响应应该是引发异常.

    【讨论】:

      猜你喜欢
      • 2014-12-09
      • 2010-10-24
      • 1970-01-01
      • 2017-11-12
      • 2013-06-22
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多