0

I am receiving a datetime string from an API that I am attempting to convert into a DateTime variable, but when I do the converse it keeps giving me the wrong time.

Here's one of the values I am getting from the api:

2020-04-21T21:44:34Z

I'm trying to bring this back as 4/21/2020 9:44:34 PM but it keeps giving me 4/21/2020 4:44:34 PM instead. (The minutes, seconds, and dates are correct.)

I've tried...

DateTime startTimeStr = Convert.ToDateTime("2020-04-21T21:44:34Z")

... and

DateTime startTimeStr = DateTime.Parse("2020-04-21T21:44:34Z");

Both give me the 4 PM time not 9 PM.

David
  • 43
  • 10

1 Answers1

1

Try calling .ToUniversalTime() on your parse result:

DateTime startTimeStr = DateTime.Parse("2020-04-21T21:44:34Z").ToUniversalTime();

Or specifying DateTimeStyles.AdjustToUniversal on corresponding Parse overload:

DateTime startTimeStr = DateTime.Parse("2020-04-21T21:44:34Z", null, DateTimeStyles.AdjustToUniversal);

Without that DateTime.Parse parses DateTime and adjusts it to your local timezone (checking DateTime.Kind property will give you DateTimeKind.Local).

Guru Stron
  • 102,774
  • 10
  • 95
  • 132