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
}
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With