Why does DateTime.Now.ToString(“u”) not work?

前端 未结 3 2062
灰色年华
灰色年华 2020-12-19 00:54

I am currently in British summer time which is UTC +1 Hour. I confirmed my PC is correct with the following code and it returns true.

System.TimeZone.Current         


        
相关标签:
3条回答
  • 2020-12-19 01:00

    "u" is the Universal sortable date/time pattern, not UTC format; To quote the documentation:

    Represents a custom date and time format string defined by the DateTimeFormatInfo..::.UniversalSortableDateTimePattern property. The pattern reflects a defined standard and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".

    When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

    Formatting does not convert the time zone for the date and time object. Therefore, the application must convert a date and time to Coordinated Universal Time (UTC) before using this format specifier.

    0 讨论(0)
  • 2020-12-19 01:15

    MSDN states the following:

    Represents a custom date and time format string defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined standard and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".

    When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

    Formatting does not convert the time zone for the date and time object. Therefore, the application must convert a date and time to Coordinated Universal Time (UTC) before using this format specifier.

    You should use the following code to convert your current Date to UTC before formatting it:

    DateTime.UtcNow.ToString("u")
    

    or

    DateTime.Now.ToUniversalTime().ToString("u")
    

    To display in the format you expected (i.e. 2009-05-27 14:21:22+01:00), you would need to use a custom date format:

    DateTime.Now.ToString("yyyy-MM-dd HH:mm:sszzz");
    
    0 讨论(0)
  • 2020-12-19 01:23

    You need to use DateTime.Now.ToUniversalTime().ToString("u").

    0 讨论(0)
提交回复
热议问题