简体   繁体   中英

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:

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.

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. 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.

Okay, so now as an answer: MSDN explains "zzz" like this:

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. It does not reflect the value of an instance's DateTime.Kind property. For this reason, the "zzz" format specifier is not recommended for use with DateTime values.

Empasis mine. 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. So - yes, it will be the same..

Your locale's timezone is probably UTC+1. Check the result after .ToUniversalTime(), it should be 14:26 (UTC+1-1 = UTC).

June is in the daylight saving period. UTC does not do daylight savings.

Strangely... or not. If you change the month from June to Jan it will be the same!

As I said daylight savings!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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