Sometimes you will have to deal with dates that come as strings, but you need to convert them to a DateTime object
Let’s take the following string as an example
Dec 1, 2020 at 11:03 AM
to be able to handle this you can do it in two ways
On this one you need to take in consideration that the string contains the word “at”, and the t character is special, so you need to pre-process the string before parsing them
string format = "MMM d, yyyy h:mm tt"; CultureInfo culture = new CultureInfo("en-US"); DateTime dt = DateTime.ParseExact(dtAsString.Replace(" at ", " "), format, culture);
And also you can escape the string data in the format variable
string format = "MMM d, yyyy 'at' h:mm tt"; CultureInfo culture = new CultureInfo("en-US"); DateTime dt = DateTime.ParseExact(dtAsString, format, culture);
COMMENTS