Search code examples
c#datetimetimezonedatetime-formatinvariantculture

C# DateTime Parse inconsistency


I´ve got a question about DateTime My Code is:

DateTime.ParseExact("2018-06-13T12:05:55.7738391Z", "yyyy-MM-ddTHH:mm:ss.fffffffZ", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ")

The result is:

"2018-06-13T14:05:55.7738391Z"

Why does the DateTime add 2 hourse? (I tried with ...00:05:55...) And how do I prevent this?


Solution

  • My guess would be you are in a time zone of UTC+2.

    var time = DateTime.ParseExact("2018-06-13T12:05:55.7738391Z", "yyyy-MM-ddTHH:mm:ss.fffffffZ", System.Globalization.CultureInfo.InvariantCulture);
    
    Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); // + 2 hours ?   
    Console.WriteLine(time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); // +0 hours ?
    

    You have said the time is UTC (Z = zulu time = UTC+0), but the timezone of your computer is automatically adding 2 hours.

    --

    And to be totally correct, you should use time.ToString("o");. You are confusing matters because your ToString contains a trailing Z, which is not added by the formatter but just copied into the output.