So I have a string that could be a date of varying formats. I wanted to create a method that tries each one until it is successful, then return the converted date, or throw an error if it matches no formats. I wrote this:
private string ConvertDate(string toConvert)
{
if (string.IsNullOrEmpty(toConvert)) { return ""; }
DateTime date;
bool success = DateTime.TryParseExact(toConvert,
"MMddyy",
new CultureInfo("en-US"),
DateTimeStyles.None,
out date);
if (!success)
{
success = DateTime.TryParseExact(toConvert,
"MMddyyyy",
new CultureInfo("en-US"),
DateTimeStyles.None,
out date);
}
if (!success)
{
success = DateTime.TryParseExact(toConvert,
"MM/dd/yy",
new CultureInfo("en-US"),
DateTimeStyles.None,
out date);
}
if (!success)
{
success = DateTime.TryParseExact(toConvert,
"MM/dd/yyyy",
new CultureInfo("en-US"),
DateTimeStyles.None,
out date);
}
if (!success) throw new Exception("Date formats are not recognized");
return date.ToString();
}
It works, but I feel pretty silly writing all that, I figure there must be an easier way to check a lot of different date formats in 1 pass. Any ideas?
This is at least easier to maintain. Although the function name is misleading. It’s should probably be something like StandardizeDateFormat.
Edit: Actually, I would probably simplify it even further like so