Convert date string to DateTime object in C#

HomeC#

Convert date string to DateTime object in C#

Escape curly braces in an interpolated string in C#
Difference between String (Uppercase s) and string (lowercase s)
Make text be “typed out” effect in C#

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

DISQUS: 0