Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a faster way to check if this is a valid date?

Is there a faster way then to simply catch an exception like below?

try
{
    date = new DateTime(model_.Date.Year, model_.Date.Month, (7 * multiplier) + (7 - dow) + 2);
}
catch (Exception)
{
    // This is an invalid date
}
like image 943
leora Avatar asked May 17 '10 13:05

leora


People also ask

How do you check if a date is valid?

To check if a date is valid: Check if the date is an instance of the Date object. Check if passing the date to the isNaN() function returns false . If both conditions are met, the date is valid.

How do you check if a date is a valid date in Python?

Python Program :split('/') isValidDate = True try: datetime. datetime(int(year), int(month), int(day)) except ValueError: isValidDate = False if(isValidDate): print("Input date is valid ..") else: print("Input date is not valid..") You can also download this program from here.

Is my date of birth valid or not?

People generally possess a variety of official documents that attest to their age and/or date of birth. Most common among these is a driver's license or DL check. For nondrivers, a check of their government-issued identification card will do the trick.

How do you check if a string is a valid date in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019")); This was the most common solution before Java 8.


2 Answers

String DateString = String.Format("{0}/{1}/{2}", model_.Date.Month, (7 * multiplier) + (7 - dow) + 2),model_.Date.Year);

DateTime dateTime;
if(DateTime.TryParse(DateString, out dateTime))
{
    // valid
}

As the comment pointed out by GenericTypeTea, this code will not run any faster than what you have now. However, I believe you gain in readability.

like image 184
Michael G Avatar answered Sep 21 '22 16:09

Michael G


If your goal is to avoid using exceptions, you could write a custom validation method:

public bool IsValidDate(int year, int month, int multiplier, int dow)
{
    if (year < 1 | year > 9999) { return false; }

    if (month < 1 | month > 12) { return false; }

    int day = 7 * multiplier + 7 - dow;
    if (day < 1 | day > DateTime.DaysInMonth(year, month)) { return false; }

    return true;
}

This performs most of the same validations as the DateTime constructor you're using - it only omits the check to see if the resulting DateTime would be less than DateTime.MinValue or greater than DateTime.MaxValue.

If you mostly get good values, this would probably be slower overall: DateTime.DaysInMonth has to do a lot of the same things the DateTime constructor does, so it would add overhead to all the good dates.

like image 33
Jeff Sternal Avatar answered Sep 18 '22 16:09

Jeff Sternal