[英]Bug in .NET's DateTime.ToString(“R”) with UTC dates?
I'm based in the UK (GMT+1 time at the moment). 我的总部位于英国(目前是格林尼治标准时间+1)。
If I run this: 如果我运行此命令:
> DateTime.UtcNow.ToString("R") // Or...
> DateTime.Now.ToUniversalTime().ToString("R")
"Mon, 06 Oct 2014 10:20:00 GMT"
Correct answer. 正确答案。
If I now run the same, without UTC DateTime conversion: 如果我现在以相同的方式运行,而没有UTC DateTime转换:
> DateTime.Now.ToString("R")
"Mon, 06 Oct 2014 11:20:00 GMT"
The time printed is correct, but the timezone is wrong. 打印的时间正确,但是时区错误。 I would expect instead:
我期望代替:
"Mon, 06 Oct 2014 11:20:00" // Or..
"Mon, 06 Oct 2014 11:20:00 BST"
Question: Is this behaviour by design? 问题: 这是设计使然吗? Can I get the same output as with the "R" format, but with the correct timezone indicator?
我可以获得与“ R”格式相同的输出,但带有正确的时区指示器吗?
It's definitely not a bug, it's the documented behaviour: 绝对不是错误,而是记录的行为:
The custom format string is
"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"
.定制格式字符串为
"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"
。 When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.使用此标准格式说明符时,格式化或解析操作始终使用不变的区域性。
...
...
Although the RFC 1123 standard expresses a time as Coordinated Universal Time (UTC), the formatting operation does not modify the value of the
DateTime
object that is being formatted.尽管RFC 1123标准将时间表示为协调世界时(UTC),但是格式化操作不会修改正在格式化的
DateTime
对象的值。 Therefore, you must convert theDateTime
value to UTC by calling theDateTime.ToUniversalTime
method before you perform the formatting operation.因此,在执行格式化操作之前,必须通过调用
DateTime.ToUniversalTime
方法将DateTime
值转换为UTC。 In contrast,DateTimeOffset
values perform this conversion automatically;相反,
DateTimeOffset
值自动执行此转换。 there is no need to call theDateTimeOffset.ToUniversalTime
method before the formatting operation.无需在格式化操作之前调用
DateTimeOffset.ToUniversalTime
方法。
As I noted in a comment on the question, 10:20 GMT is correct, assuming that you ran the code shortly before asking the question: 11:20 GMT has not occurred yet. 正如我在对该问题的评论中所指出的那样,假设您在提出问题之前不久就运行了代码:11:20 GMT尚未发生,那么10:20 GMT是正确的。
So basically, when you follow the guidance in the documentation and call ToUniversalTime
, it does the right thing. 因此,基本上,当您按照文档中的指导进行操作并调用
ToUniversalTime
,它会做正确的事情。 When you don't, it gives a misleading value - that's unfortunate, but part of the broken design of DateTime
IMO. 如果您不这样做,它会产生误导性的价值-不幸的是,但这是
DateTime
IMO损坏的设计的一部分。
You should consider at least using DateTimeOffset
, or potentially using my Noda Time project instead. 您应该考虑至少使用
DateTimeOffset
,或者可能使用我的Noda Time项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.