It's not enough to use DateTime.ParseExact or DateTime.TryParseExact. The / is a special formatting character, the date separator character. In a format string it will be replaced with whatever the date separator is for the application's current culture. It can't be escaped because it is not a special character like \. This will cause problems if your system's culture uses . (Russia and other countries).
To specify a different date separator you need to create a CultureInfo object with the separator you want. The following function accepts a list of separators and tries to parse dates using each separator until one of them succeeds:
public static bool TryParseDate(string input, string[] separators, out DateTime date)
{
var ci = (CultureInfo) CultureInfo.InvariantCulture.Clone();
foreach (var separator in separators)
{
ci.DateTimeFormat.DateSeparator = separator;
DateTime result;
if (DateTime.TryParseExact(input, "dd/MM/yyyy", ci, DateTimeStyles.None,
out date))
return true;
}
date=new DateTime();
return false;
}
There's no need to define multiple formats because dd/MM/yyyy matches all cases.
This allows you to write code like the following snippet:
var separators = new []{"/",".",",","-"};
DateTime result;
var success1 = TryParseDate("12.05.2015", separators, out result);
var success2 = TryParseDate("12/05/2015", separators, out result);
var success3 = TryParseDate("12,05,2015", separators, out result);
var success4 = TryParseDate("12-05-2015", separators, out result);
I added - because I see it's a common separator in Germany. You can make the function even more generic by passing the format as another parameter.
TryParseExact accepts multiple format parameters. If it weren't for the / separator, you could write a single call with all formats:
var formats=new []{"dd.MM.yyyy","dd,MM,yyyy","dd-MM-yyyy"};
DateTime result;
var success=DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture, DateTimeStyles.None,
out date)
-then. I see from Wikipedia that it's used as a separator in Germany, France