Your problem here is that since the compiler only sees two digits/two digits/two digits
in both cases, it has no way to know that you want day/month/year
instead of month/day/year
until it tries to actually casts, and notices that your value for the month is >= 12
.
You could solve this by splitting the date on /
, and throwing in the arguments in the "correct" order to the compiler, like so:
string[] dateParts = input.Split("/");
int day; int month; int year;
// You could use a boolean variable here to double-check that all casts are successful
Int32.TryParse(dateParts[0], out day);
Int32.TryParse(dateParts[1], out month);
Int32.TryParse(dateParts[2], out year);
var output = new DateTime(year, month, day);
If you put this in a separate function you could use it like this to support both formats:
DateTime releaseDate;
try
{
// will throw exception if input is not in the default format
releaseDate = new DateTime(input);
}
catch (InvalidFormatException ex)
{
releaseDate = GetDateTimeFromNonStandardInput(input);
}
catch
{
throw; // or do whatever error handling you feel like.
}
Personally, I'd write the GetDateTimeFromNonStandardInput()
as an extension method to the DateTime
class.