Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Convert a string "yyyy-MM-dd hh:mm:ss 'UTC'" to date time

i have a string, as an example:
"2022-04-17 14:46:31 UTC"

And i want to convert it to date time but i have got the following error:
{"The string ‘2022-04-17 14:46:31 UTC’ was not recognized as a valid DateTime. There is an unknown word starting at index ’20’."}

Notice that i have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. var date = DateTime.Parse("2022-04-17 14:46:31 UTC")

2.DateTime dt; DateTime.TryParseExact("2022-04-17 14:46:31 UTC", "yyyy-MM-dd hh:mm:ss 'UTC'", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)

>Solution :

There are two things to be done:

  1. as mentioned in the comments: use HH for the 24 hour format
  2. adjust the result to an actual UTC time
DateTime.TryParseExact("2022-04-17 14:46:31 UTC", "yyyy-MM-dd HH:mm:ss 'UTC'", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
DateTime utc = new DateTime(dt.Ticks,  DateTimeKind.Utc);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading