Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a valid date

Tags:

date

c#

datetime

So I'm trying to figure out if there is another kind of way to check if a date is valid. So the idea is that if the date is valid then it continue's using the given date, if the date is invalid is uses the date of today.

This is what I got at the moment:

        public void setBirthdate(int year, int month, int day)
        {
        if (month < 1 || month > 12 || day < 1 || day > DateTime.DaysInMonth(year, month))
        {
            Birthdate = DateTime.Today;
        }
        else
            Birthdate = new DateTime(year, month, day);
        }   

So is there any shorter/more readable way of doing this?

Thanks in advance

like image 544
RandomPerson Avatar asked Dec 27 '14 18:12

RandomPerson


2 Answers

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;
}
like image 92
Grant Winney Avatar answered Sep 28 '22 05:09

Grant Winney


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;
}
like image 29
Jason Faulkner Avatar answered Sep 28 '22 03:09

Jason Faulkner