为什么DateTime.Now.ToString(" U")无法正常工作?无法正常、工作、Now、DateTime

2023-09-03 16:21:26 作者:野兽迷情

我目前在英国夏令时间这是UTC +1小时。我证实了我的电脑是正确的下面的code和返回true。

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.CurrentTimeZone.IsDaylightSavingTime(Date.Now)

我的问题是那么为何UTC格式化无法正常工作,我所期望的:

My question is then why does the UTC formatter not work as I would expect:

DateTime.Now.ToString("u")

据UTC格式返回如下确切的当前系统日期的预期,但与Z(祖鲁时间)结尾不是+01:00

It returns the exact current system date as below in UTC format as expected but with the Z (Zulu Time) at the end not +01:00?

2009-05-27 14:21:22Z

不是

2009-05-27 14:21:22+01:00

这是正确的功能?

Is this correct functionality?

推荐答案

MSDN规定如下:

再presents由DateTimeFormatInfo.UniversalSortableDateTimePattern属性定义的自定义日期和时间格式字符串。该模式反映了一个定义的标准,并且属性是只读的。因此,它总是相同,而不管所使用的培养物或提供的格式提供的。自定义格式字符串为yyyy' - 'MM' - 'DD HH:毫米:ss'Z'。

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.

格式不转换的日期和时间对象的时区。因此,应用程序必须使用此格式说明符之前转换的日期和时间,以协调世界时(UTC)。

您应使用以下code到当前的日期转换为UTC格式化之前:

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

DateTime.UtcNow.ToString("u")

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

要在你希望的格式显示(即2009-05-27 14:21:22 + 01:00),您将需要使用自定义日期格式:

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");