Вы можете решить эту проблему парой звонков на TryParseExact :
public static DateTime ParseDate(string input)
{
DateTime result;
if (DateTime.TryParseExact(input, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;
if (DateTime.TryParseExact(input, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;
throw new FormatException();
}
Проведите быструю проверку:
public static void Main()
{
string[] tests = new string[] { "2018-06-29", "29-06-2018","Invalid" };
foreach (var t in tests)
{
var result = ParseDate(t);
Console.WriteLine( "Year: {0} Month: {1} Day: {2}", result.Year, result.Month, result.Day );
}
}
Выход:
Year: 2018 Month: 6 Day: 29
Year: 2018 Month: 6 Day: 29
Run-time exception (line 18): One of the identified items was in an invalid format.
Пример кода на DotNetFiddle