DateTime.TryParseExact
method has an overload which takes your formats as a string array.
string s = "";
DateTime dt;
var array = new[] {"MM/dd/yyyy", "dd/MM/yyyy", "yyyy-MM-dd"};
if(DateTime.TryParseExact(s, array, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
//
}
I used InvariantCulture
as a IFormatProvider
because /
format specifier has a special meaning of replace me with current culture or supplied culture date separator. That means, if you use CurrentCulture
and it doesn't have /
as a DateSeparator
, your parsing will fail even if your string and format exactly matches.
But remember
This way is okey for your examples.
But string like 01/02/2015
is a problem because this method can't know that this is 1 February 2015
or 2 January 2015
. In such a case, this method parse your string with first successfully matched format.
However I am not certain of the format of the string.
If you want to full successfully parse for your all examples, you have to know their exact formats.