I want to parse a string that represent a DateTime in UTC format.
My string representation includes the Zulu time specification which should indicate that the string represent a UTC time.
var myDate = DateTime.Parse("2012-09-30T23:00:00.0000000Z");
From the above I would expect myDate.Kind to be DateTimeKind.Utc, instead it is DatetimeKind.Local.
What am I doing wrong and how to Parse a string that represents a UTC time?
Many thanks!
I would use my Noda Time project personally. (Admittedly I’m biased as the author, but it would be cleaner…) But if you can’t do that…
Either use
DateTime.ParseExactspecifying the exact format you expect, and includeDateTimeStyles.AssumeUniversalandDateTimeStyles.AdjustToUniversalin the parse code:(Quite why it would adjust to local by default without
AdjustToUniversalis beyond me, but never mind…)EDIT: Just to expand on my objections to mattytommo’s suggestion, I aimed to prove that it would lose information. I’ve failed so far – but in a very peculiar way. Have a look at this – running in the Europe/London time zone, where the clocks go back on October 28th in 2012, at 2am local time (1am UTC):
It looks like there’s a “with or without DST” flag being stored somewhere, but I’ll be blowed if I can work out where. The docs for
TimeZoneInfo.ConvertTimeToUtcstateThat doesn’t appear to be the case here when converting
local2…EDIT: Okay, it gets even stranger – it depends which version of the framework you’re using. Consider this program:
So this takes two different UTC values, parses them with
DateTime.Parse, then converts them back to UTC in two different ways.Results under .NET 3.5:
Results under .NET 4.5 beta: