Reputation: 26058
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?
Upvotes: 0
Views: 467
Reputation: 33809
Try something like this. Assuming MM
is always first and year is 2000 or later
(for yy
format)
string date = "10/25/2011";
string[] arr = date.ToArray()
.Where(ch => ch > 47 && ch < 58 ) //Filter out all but numbers
.Select(s => s.ToString()).ToArray();
if(arr.Length >5)
{
string ISOformattedDate = string.Format( arr.Length == 6 ?
"{4}{5}-{0}{1}-{2}{3}T00:00:00" :
"{4}{5}{6}{7}-{0}{1}-{2}{3}T00:00:00", arr);
DateTime mydate = Convert.ToDateTime(ISOformattedDate);
}
Upvotes: 1
Reputation: 7309
This is at least easier to maintain. Although the function name is misleading. It's should probably be something like StandardizeDateFormat.
private string ConvertDate(string toConvert)
{
if (string.IsNullOrEmpty(toConvert)) { return ""; }
string[] dateFormats = new string[]{"MMddyy","MMddyyyy","MM/dd/yy","MM/dd/yyyy"};
DateTime date;
bool success = false;
for(int i = 0;i<dateFormats.Length &&!success;i++)
{
success = DateTime.TryParseExact(toConvert,
dateFormats[i],
new CultureInfo("en-US"),
DateTimeStyles.None,
out date);
}
if (!success) throw new Exception("Date formats are not recognized");
return date.ToString();
}
Edit: Actually, I would probably simplify it even further like so
private string ConvertDate(string toConvert)
{
if (string.IsNullOrEmpty(toConvert)) { return ""; }
string[] dateFormats = new string[]{"MMddyy","MMddyyyy","MM/dd/yy","MM/dd/yyyy"};
DateTime date;
for(int i = 0;i<dateFormats.Length ;i++)
{
if(DateTime.TryParseExact(toConvert, dateFormats[i], new CultureInfo("en-US"), DateTimeStyles.None, out date))
return date.ToString();
}
throw new Exception("Date formats are not recognized");
}
Upvotes: 3