LB.
LB.

Reputation: 14112

Parsing DateTime

How would one parse 1900-01-01 00:00:00Z into a DateTime object?

        string temp = "1900-01-01 00:00:00Z";
        CultureInfo provider = CultureInfo.InvariantCulture;
        var date = DateTime.ParseExact(temp, "yyyy-MM-dd hh:mm:ssZ", provider);

this returns me:

12/31/1899 7:00:00 PM

Upvotes: 2

Views: 499

Answers (4)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61982

By default, the time given is adjusted to the local time zone of your machine. The date.Kind should reflect that. If instead you want the time adjusted to Universal Time (UTC), use DateTimeStyles.AdjustToUniversal flag as the fourth parameter to ParseExact.

Upvotes: 0

Shyam sundar shah
Shyam sundar shah

Reputation: 2523

You can use this code

        DateTime a;
        var dt = DateTime.TryParse("30/05/1970",out a);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502016

How are you displaying the value? I suspect it's just applying your local time zone to the date.

For example, try printing out:

  • date.Year
  • date.Kind
  • date.Hour

My guess is that you'll see date is actually a UTC DateTime with the right value.

It's unfortunate that .NET is performing the time zone conversion for you implicitly, but then the date and time types in .NET leave something to be desired anyway :(

An alternative would be to use DateTimeOffset which should make it slightly clearer.

Upvotes: 3

Hogan
Hogan

Reputation: 70529

I'm guessing you are in EST. It is subtracting 5 hours from the time. Maybe this is because of how you printing out the time? Try printing it in GMT. Or you could parse it with your local timezone.

Upvotes: 4

Related Questions