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

Keep getting FormatException on DateTime.ParseExact

I am trying to convert a date stored as string to DateTime using DateTime.ParseExact like below

var myDate = DateTime.ParseExact("3/14/2023 4:08:30 PM", "M/dd/yyyy h:mm:ss tt", null);

but I keep getting a FormatExceptionerror on that line.

I have tried tweaking the format, but nothing works. What am I missing here?

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

>Solution :

Your existing code uses the default culture from the currently-executing thread. Even though you’ve specified a custom date/time format string, the culture can still affect it:

  • It affects how numbers are parsed (as not every culture uses ‘0’-‘9’)
  • It affects which calendar system the value is interpreted in
  • It affects the date separators (between year, month and day)
  • It affects the time separators (between hour, month and minute)
  • It affects the strings used for AM and PM

Unless the text has come from a user, it’s usually best to explicitly specify CultureInfo.InvariantCulture as the culture to parse in – at which point you know (or can know) exactly what will be used for each of the variations above.

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