0

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?

Felix Arnold
  • 839
  • 7
  • 35
  • It will likely be a time zone issue. – Stevo Jul 18 '18 at 09:54
  • 2
    Try it with `.ToUniversalTime()` before the `ToString`. – Stevo Jul 18 '18 at 09:56
  • 1
    Other option is to use styles, eg. `DateTimeStyles.AdjustToUniversal` in `ParseExact()`. One thing to fix would be the format, at the end you should have *K* for kind, not *Z*, unless you actually assume that date-time will by only UTC. – kiziu Jul 18 '18 at 10:04
  • Preferably, `DateTimeStyles.RoundTripKind` would be better, since the `Z` maps to `DateTimeKind.Utc` nicely. – Matt Johnson-Pint Jul 18 '18 at 17:00

1 Answers1

2

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.

Neil
  • 11,059
  • 3
  • 31
  • 56