简体   繁体   中英

Bug in .NET's DateTime.ToString(“R”) with UTC dates?

I'm based in the UK (GMT+1 time at the moment).

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:

> 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?

It's definitely not a bug, it's the documented behaviour:

The custom format string is "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. Therefore, you must convert the DateTime value to UTC by calling the DateTime.ToUniversalTime method before you perform the formatting operation. In contrast, DateTimeOffset values perform this conversion automatically; there is no need to call the DateTimeOffset.ToUniversalTime method before the formatting operation.

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.

So basically, when you follow the guidance in the documentation and call ToUniversalTime , it does the right thing. When you don't, it gives a misleading value - that's unfortunate, but part of the broken design of DateTime IMO.

You should consider at least using DateTimeOffset , or potentially using my Noda Time project instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM