Search code examples
c#datetimetype-conversion

.NET c#: Convert string (ej. "Mar 26, 2021 at 7:17 PM") to DateTime object


I am trying to create a DateTime object from strings like

Dec 1, 2020 at 11:03 AM
Mar 26, 2021 at 7:17 PM
Oct 21, 2020 at 3:07 PM

I am using this but it throws error:

string format = "MMM d, yyyy at h:mm tt";
CultureInfo culture = new CultureInfo("en-US");
DateTime dt = DateTime.ParseExact(dtAsString, format, culture);

What am I doing wrong?


Solution

  • The t character in the word at is special. You may want to pre-process the strings before parsing:

    string format = "MMM d, yyyy h:mm tt";
    CultureInfo culture = new CultureInfo("en-US");
    DateTime dt = DateTime.ParseExact(dtAsString.Replace(" at ", " "), format, culture);
    

    See it work here:

    https://dotnetfiddle.net/hmOW6K

    You can also escape the text data in the format:

    string format = "MMM d, yyyy 'at' h:mm tt";
    CultureInfo culture = new CultureInfo("en-US");
    DateTime dt = DateTime.ParseExact(dtAsString, format, culture);
    

    See it here:

    https://dotnetfiddle.net/lde3ws