user712923
user712923

Reputation: 1555

Looking for a better way to validate a date in c# 4

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

=============

Upvotes: 0

Views: 237

Answers (1)

Anthony Pegram
Anthony Pegram

Reputation: 126834

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 is 1/1/1753. Later, you reject all years below 1900. As such, the checks on the MinValue fields 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?

Upvotes: 2

Related Questions