I am creating date using following code
try
{
newdatetime = new DateTime(2012, 2, 30);
break;
}
catch (ArgumentOutOfRangeException)
{
// Try 29 Feb if not 28.
}
The catch block is to catch the invalid date like 30 Feb. Is there any way to verify if the date is valid by speciying the parameters like (year, month, day)?
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
DateTimecan 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:
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.