开发者

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

  • 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 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜