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