Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Validate an int-based DateTime without exceptions?

This question talks about validating a string representing a date, and in it folks mention that it's good to avoid using Exceptions for regular flow logic. And TryParse() is great for that. But TryParse() takes a string, and in in my case i've already got the year month and day as integers. I want to validate the month/day/year combination. For example February 30th.

It's pretty easy to just put a try/catch around new DateTime(int, int, int), but I'm wondering if there's a way to do it without relying on exceptions.

I'd also feel silly composing these ints into a string and then using TryParse().

like image 762
orion elenzil Avatar asked Feb 27 '26 01:02

orion elenzil


1 Answers

The following will check for valid year/month/day combinations in the range supported by DateTime, using a proleptic Gregorian calendar:

public bool IsValidDate(int year, int month, int day)
{
    return year >= 1 && year <= 9999
            && month >= 1 && month <= 12
            && day >= 1 && day <= DateTime.DaysInMonth(year, month);
}

If you need to work with other calendar systems, then expand it as follows:

public bool IsValidDate(int year, int month, int day, Calendar cal)
{
    return year >= cal.GetYear(cal.MinSupportedDateTime)
            && year <= cal.GetYear(cal.MaxSupportedDateTime)
            && month >= 1 && month <= cal.GetMonthsInYear(year)
            && day >= 1 && day <= cal.GetDaysInMonth(year, month);
}
like image 55
Matt Johnson-Pint Avatar answered Feb 28 '26 21:02

Matt Johnson-Pint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!