orion elenzil orion elenzil -4 years ago 136
C# Question

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().

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download