为什么DateTime.Now.ToString(“u”)不起作用? [英] Why does DateTime.Now.ToString("u") not work?

查看:210
本文介绍了为什么DateTime.Now.ToString(“u”)不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在英国夏令时间,这是UTC +1小时。我确认我的电脑是正确的以下代码,它返回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")

它按照预期的方式返回确切的当前系统日期,如下所示,但使用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?

ie

2009-05-27 14:21:22Z

不是

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

这是正确的功能吗?

推荐答案

MSDN陈述以下内容:

MSDN states the following:


表示由DateTimeFormatIn定义的自定义日期和时间格式字符串fo.UniversalSortableDateTimePattern属性。该模式反映了一个定义的标准,属性是只读的。因此,无论使用的文化或提供的格式提供者,它总是相同的。自定义格式字符串为yyyy - 'MM' - 'dd HH':​​'mm':'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)。

在格式化之前,您应该使用以下代码将当前日期转换为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");

这篇关于为什么DateTime.Now.ToString(“u”)不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆