views:

56

answers:

4
+2  Q: 

Parsing Datetime

I have a date time as a string, eg. "2010-08-02", I'm trying to convert it to UTC with the following code snippet

DateTime.ParseExact("2010-08-02Z", "yyyy-MM-ddZ", CultureInfo.InvariantCulture)

When I print to the console, I get the following: 8/1/2010 5:00:00 PM. Is there a reason why the date shows up as the date before the date I'm trying to parse? I could just add a day to this to advance to the original day, but I wanted to see if there's anything I'm doing wrong in the formatting that's causing this.

+3  A: 

EDIT: I had a mixture of being correct and not :)

It's showing you the local time represented by the UTC string. It's annoying that DateTime doesn't make this sort of thing clear, IMO. Additionally, I don't think you want to use 'Z' as the format specifier for the time zone; that's not actually a valid format specifier; it should be 'z', - but that's meant for things like "+01:00". I think you should be using 'K'. Frankly it's not clear, but if you use 'K' it round-trips correctly, certainly ('Z' roundtrips too, but only because it ignores it, treating it as plain text).

You can fix it by just calling ToUniversalTime, or (preferred IMO) specifying DateTimeStyles.AdjustToUniversal as an extra argument:

DateTime dt = DateTime.ParseExact("2010-08-02Z", "yyyy-MM-ddK",
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.AdjustToUniversal);
Jon Skeet
Z means to Zulu time (GMT 0) which means if you are in a timezone that is lower than Zulu time , the hours in difference are substracted from that date, bringing us back to the day before at certain times of the day...fun! Example, it is areay Friday in Tokyo when it is still thursday evening in LA, So it is perhaps friday very early in the morning in Dehli when it is still Thursday in London near Cutty Sark ;).
Caspar Kleijne
+1  A: 

The UTC of midnight for 2010-08-02 happens to be at 5pm on 2010-08-01.

Shawn de Wet
A: 

If the original string is just a date in the format "2010-08-02" (without the Z), then why not just:

DateTime.SpecifyKind(
    DateTime.ParseExact("2010-08-02", 
         "yyyy-MM-dd", 
         CultureInfo.InvariantCulture),
         DateTimeKind.Utc);

ParseExact will presumably return a DateTime with Kind = Unspecified, and you can make it UTC or Local as you wish using SpecifyKind.

Joe
A: 

Thank you all for your invaluable information. I stand enlightened.

kingrichard2005