Search code examples
c#datetimeiformatprovider

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


Solution

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