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.

2
  • @David What timezone do you live in? Commented Jun 15, 2020 at 22:07
  • Did the comments at stackoverflow.com/a/1756699/34092 help (i.e. AdjustToUniversal)? Commented Jun 15, 2020 at 22:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yep. That did it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.