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

c# convert string to DateTime format

I am reading a string value from DataTable which is in the format :

"3/29/2022 6:32:05 PM"

How do I convert this string in this format:

"03292022"

I tried this:

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

string format= "MMddyyyy";
string dateString =  "3/29/2022 6:32:05 PM";
DateTime dateValue;

if (DateTime.TryParseExact(dateString, format,
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out dateValue))
   Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
   Console.WriteLine("Unable to convert '{0}' to a date.", dateString);

>Solution :

You have to first parse the date from the original format:

if (DateTime.TryParseExact(dateString, "M/dd/yyyy h:mm:ss tt",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out dateValue))

The "Exact" in ParseExact() isn’t just for show: you have to have the format string here perfect, including single vs double letters for date parts like month, as well as upper-case vs lower-case for date parts like hour.

Then you can output the date in the desired format:

Console.WriteLine($"Converted '{dateString}' to {dateValue:MMddyyyy}.");

Remember that DateTime values themselves do not have any human-readable format, so you have to specify the format again every time you output it or convert it back to a string. Also remember cultural/internationalization issues mean these conversions are far slower and more error-prone than you’d expect: something to avoid.

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