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 theDateTime
value to UTC by calling theDateTime.ToUniversalTime
method before you perform the formatting operation. In contrast,DateTimeOffset
values perform this conversion automatically; there is no need to call theDateTimeOffset.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.
See more on this question at Stackoverflow