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