I have a list of different DateTime formats and I want to convert all of them in one specific format. It works fine, until I hit this line: 9.13.2023 2:06:58 PM. On this line i get an System.FormatException. But the line 9.13.2023 6:38:50 AM works fine. Do i overlook something?
string oldDate = oldDateFromFile;
string format1 = "MM.dd.yyyy HH:mm";
string format2 = "MM.dd.yyyy HH:mm:ss tt";
string format3 = "M.dd.yyyy HH:mm:ss tt";
string format4 = "M.dd.yyyy H:mm:ss tt";
string formatOutput = "yyyy-MM-dd HH.mm.ss";
string[] formats = { format1, format2, format3, format4 };
var newDate = DateTime.ParseExact(oldDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
using (StreamWriter writetext = new StreamWriter($@"{mainFolderPath}new_date.txt", append: true))
{
writetext.WriteLine(newDate.ToString(formatOutput));
writetext.Close();
}
HH
is for hours 00-23, for a 24-hour clock. The parser gets confused because it encounters an impossible scenario, it’s 01 (with a 24-hour clock) but also PM. Seeing the contradiction, the parser just assumes that it can’t match using this pattern and tries to find another, runs out, and throws the exception because no format matches.
For 12 hour clocks (with AM/PM), use hh
or h
instead.
string format1 = "MM.dd.yyyy hh:mm";
string format2 = "MM.dd.yyyy hh:mm:ss tt";
string format3 = "M.dd.yyyy hh:mm:ss tt";
string format4 = "M.dd.yyyy h:mm:ss tt";
string formatOutput = "yyyy-MM-dd HH.mm.ss";