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

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

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 :

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

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