Wondering if there is a better way to validate A date,
public static bool ValidDate(this DateTime value)
{
if (value == DateTime.MinValue) return false;
if (value == DateTime.MaxValue) return false;
var validSqlDate = ((value >= (DateTime)SqlDateTime.MinValue) && (value <= (DateTime)SqlDateTime.MaxValue));
if (!validSqlDate) return false;
if (value.Year <= 1900) return false;
return true;
}
Any suggestions
EDITED Added Rules
- DateTime cannot be empty
- if has value it should be safe to save in to sql server
- I had scenarios where the date were set to 1900.Is this some sort of MinValue
=============
A better way is to write just the amount of code you need to fulfill your goal.
DateTime.MinValue is
1/1/0001. SqlDateTime.MinValue is1/1/1753. Later, you reject all years below 1900. As such, the checks on theMinValuefields are redundant, get rid of them.DateTime.MaxValue and SqlDateTime.MaxValue are the same thing. You do not need both checks, drop the SqlDateTime comparison.
So ultimately, your function is
return value.Year > 1900 && value < DateTime.MaxValue;Is accepting all dates from January 1, 1901 through December 31, 9999 your business goal?