简体   繁体   English

为什么DateTime.ToString没有按预期给出时区

[英]Why does DateTime.ToString not give timezone as expected

If I have this code: 如果我有这个代码:

                DateTime dt = DateTime.UtcNow;
                string sDate = dt.ToString("yyyy-MM-dd HH:mm:ss.fff zz");

my sDate looks like this: 我的sDate看起来像这样:

"2013-04-07 21:05:15.396 +10"

which is the current UTC datetime (9:05pm), but with a "+10" on the end which is my local timezone. 这是当前的UTC日期时间(晚上9:05),但结尾是“+10”,这是我当地的时区。

I would have expected this: 我原以为这个:

"2013-04-07 21:05:15.396 +00"

what's going on? 这是怎么回事?

That's because the documentation says (emphasis mine): 那是因为文档说(强调我的):

With DateTime values, the "zz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours. 使用DateTime值,“zz”自定义格式说明符表示本地操作系统的时区与UTC的签名偏移量,以小时为单位。 It does not reflect the value of an instance's DateTimeKind property. 它不反映实例的DateTimeKind属性的值。 For this reason, the "zz" format specifier is not recommended for use with DateTime values. 因此,建议不要将“zz”格式说明符与DateTime值一起使用。

So, the zz format specifier always outputs the UTC offset of your local timezone, even when used to format UTC times. 因此, zz格式说明符始终输出本地时区的UTC偏移量,即使用于格式化UTC时间也是如此。

DateTime.ToString , when you don't pass a CultureInfo into it, defaults to the current culture. DateTime.ToString ,当您不将CultureInfo传递给它时,默认为当前文化。 If your current culture is +10, then that explains why you see +10. 如果您当前的文化是+10,那么这就解释了为什么你看到+10。 There's various FxCop and Code Analysis rules you can turn on to warn you when you call ToString without a CultureInfo 您可以打开各种FxCop和代码分析规则,以便在没有CultureInfo情况下调用ToString时发出警告

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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