kingrichard2005
kingrichard2005

Reputation: 7269

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.

Upvotes: 2

Views: 738

Answers (3)

to StackOverflow
to StackOverflow

Reputation: 124696

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

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);

Upvotes: 3

Shawn de Wet
Shawn de Wet

Reputation: 5976

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

Upvotes: 1

Related Questions