DateTime to RFC-1123 gives inaccurate timezone

烂漫一生 提交于 2019-12-10 18:59:49

问题


If I get the RFC-1123 formatted date of a DateTime object, it gives the current local time, but gives the timezone as GMT (which is inaccurate).
DateTime.Now.ToString("r");
returns
Fri, 12 Feb 2010 16:23:03 GMT

At 4:23 in the afternoon, but my timezone is UTC+10 (plus, we're currently observing daylight saving time).

Now, I can get a return value that's "correct" by converting to UTC first:
DateTime.UtcNow.ToString("r");
returns
Fri, 12 Feb 2010 05:23:03 GMT

However, ideally, I'd like to get the right timezone, which I guess would be
Fri, 12 Feb 2010 16:23:03 +1100

Passing in the current CultureInfo doesn't change anything. I could get a UTC offset with TimeZoneInfo.Local.GetUtcOffset(...) and format a timezone string from that, but stripping out the GMT bit and replacing it seems gratutiously messy.

Is there a way to force it to include the correct timezone?


回答1:


The .NET implementation always expresses the result as if it were GMT, irrespective of the time offset of the actual date.

By using DateTime.Now.ToString("r"); you're essentially saying String.Format("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", DateTime.Now);, which is the .NET RFC1123 format string, as indicated on MSDN - The RFC1123 ("R", "r") Format Specifier.

To get the behaviour you require, you should probably use String.Format, and replace the fixed 'GMT' section of the specifier with a time offset specifier:

  • The "z" Custom Format Specifier
  • The "zz" Custom Format Specifier
  • The "zzz" Custom Format Specifier



回答2:


You could just do DateTime.UtcNow.ToString ("R"), you will still get GMT timezone but the time is correctly offset then.



来源:https://stackoverflow.com/questions/2249889/datetime-to-rfc-1123-gives-inaccurate-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!