Well, with months you know the valid range so you can constrain that manually. Years are obviously not constrained in the normal sense, but are instead limited by the amount that DateTime
can actually hold (0001 to 9999).
With days, there is the DaysInMonth(int year, int month)
method that can tell you the maximum days for the provided month. This also gives you the leap year.
With this information, you can create your own method to check the range based on the provided integers.
Something like:
public static bool AreValidDateValues(int year, int month, int day)
{
if (month < 1 || month > 12)
return false;
if (year < DateTime.MinValue.Year || year > DateTime.MaxValue.Year)
return false;
var days = DateTime.DaysInMonth(year, month);
if (day < 1 || day > days)
return false;
return true;
}
Or if you can't be bothered with that, convert the raw values into a string representation of a date and put that into DateTime.TryParse
, which will give a true/false for the provided string - just be careful with culture-sensitive parsing.