Check for a valid date

You could use the values to try constructing a valid DateTime, then catch the ArgumentOutOfRangeException that occurs if the arguments are out of range:

public void setBirthdate(int year, int month, int day)
{
    try
    {
        Birthdate = new DateTime(year, month, day);
    }
    catch (ArgumentOutOfRangeException)
    {
        Birthdate = DateTime.Today;
    }
}

Some may disagree with using exceptions like this, but I'm just letting the DateTime class do its own checks, instead of recreating them myself.

From the documentation, an ArgumentOutOfRangeException occurs if:

  • Year is less than 1 or greater than 9999, or
  • Month is less than 1 or greater than 12, or
  • Day is less than 1 or greater than the number of days in month.

Alternatively, you could copy the logic from the DateTime class: (reference)

public void setBirthdate(int year, int month, int day)
{
    if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
    {
        int[] days = DateTime.IsLeapYear(year)
            ? new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
            : new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};

        if (day >= 1 && day <= days[month] - days[month - 1])
            Birthdate = new DateTime(year, month, day);
    }
    else
        Birthdate = DateTime.Today;
}

I would use the TryParse (MSDN) method over exception catching (which can be high overhead if called frequently with invalid values):

DateTime date;
if (DateTime.TryParse(string.Format("{0}-{1}-{2}", year, month, day), out date))
{
    // Date was valid.
    // date variable now contains a value.
}
else
{
    // Date is not valid, default to today.
    date = DateTime.Today;
}

Tags:

C#

Datetime

Date