RFC-1123的DateTime给出了不准确的时区 [英] DateTime to RFC-1123 gives inaccurate timezone

查看:1525
本文介绍了RFC-1123的DateTime给出了不准确的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我获得了DateTime对象的RFC-1123格式化日期,它将显示当前的本地时间,但将时区指定为GMT(这是不准确的)。

DateTime .Now.ToString(r);

返回

Fri,12 Feb 2010 16:23:03 GMT



在下午4点23分,但我的时区是UTC + 10(另外,我们正在观察夏令时) / p>

现在,我可以通过转换为UTC来获得正确的返回值:

DateTime.UtcNow.ToString (r);

返回

Fri,2010年02月12日05:23:03 GMT



然而,理想情况下,我想获得正确的时区,我猜这将是

Fri ,2010年2月12日16:23:03 +1100



传递当前的CultureInfo不会更改任何内容。我可以通过TimeZoneInfo.Local.GetUtcOffset(...)获得UTC偏移量,并格式化时区字符串,但剥离了GMT位,并将其替换似乎令人无礼。



有没有办法强制包含正确的时区?

解决方案

.NET实现总是表示结果,就好像它是GMT,不管实际日期的时间偏移。



使用 DateTime.Now.ToString(r); 你本质上是说 String.Format(ddd,dd MMM yyyy HH':​​'mm':'ss'GMT ',DateTime.Now); ,它是.NET RFC1123格式的字符串,如MSDN所示 - RFC1123(R,r)格式说明符



要获取您应该使用 String.Format ,并用说明符替换固定的GMT部分与时间偏移说明符:




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?

解决方案

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:

这篇关于RFC-1123的DateTime给出了不准确的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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