简体   繁体   English

C#中的这种日期行为有什么问题?

[英]What's wrong with this date behavior in C#?

If I output a formatted date as follows: 如果我输出的格式化日期如下:

DateTime.Parse("2010-06-02T15:26:37.789 +01:00").ToString("HH:mm:sszzz")

I get the expected result: 我得到了预期的结果:

15:26:37+01:00

However, if I parse the same date, convert to UTC and output with the same format as follows: 但是,如果我解析相同的日期,请转换为UTC并以相同的格式输出,如下所示:

DateTime.Parse("2010-06-02T15:26:37.789 +01:00").ToUniversalTime().ToString("HH:mm:sszzz")

I get this: 我得到这个:

14:26:37+01:00

Now those two dates, the local and UTC versions, should be exactly the same but the outputted text represents two different times. 现在,这两个日期(本地和UTC版本)应该完全相同,但是输出的文本表示两个不同的时间。

Why is this? 为什么是这样?

EDIT 编辑

To clarify, I expected the time in UTC to be 14:26:37 as the DST element is removed by UTC. 为了明确起见,我预计UTC中的时间为14:26:37,因为DST元素已被UTC删除。 I didn't expect it to still have an offset. 我没想到它还会有抵消。 The two above times are not equivalent, whereas 15:26:37+ 01:00 and 14:26:37+ 00:00 are. 以上两个时间并不相等,而15:26:37+ 01:00和14:26:37+ 00:00是相等的。

Okay, so now as an answer: MSDN explains "zzz" like this: 好的,现在作为答案: MSDN这样解释“ zzz”:

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

Empasis mine. Empasis我的。 English's not my native language, but I read that as "zzz" being the machine's offset, not related to the DateTime value at all. 英文不是我的母语,但我将其读为“ zzz”是机器的偏移量,与日期时间值完全无关。 So - yes, it will be the same.. 所以-是的,它将是相同的。

Your locale's timezone is probably UTC+1. 您所在地区的时区可能是UTC + 1。 Check the result after .ToUniversalTime(), it should be 14:26 (UTC+1-1 = UTC). 在.ToUniversalTime()之后检查结果,该结果应为14:26(UTC + 1-1 = UTC)。

June is in the daylight saving period. 六月是夏令时。 UTC does not do daylight savings. UTC不会节省夏令时。

Strangely... or not. 奇怪...还是没有。 If you change the month from June to Jan it will be the same! 如果您将月份从6月更改为1月,则将保持不变!

As I said daylight savings!!! 正如我所说的夏令时!

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

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