3

我想知道是否有任何巧妙的方法来检查数据是否在允许的范围内。我的意思是在 c# 中,我们可以表示从 0001-01-01 到(我认为)9999-01-01 的数据。但是,如果我们尝试做类似的事情

 DateTime result = DateTime.Parse("0001-01-01").Subtract(TimeSpan.FromDays(1)) 

我得到一个例外。是否有任何巧妙的方法来检查是否可以进行 DateTime 操作(加减法等)

4

4 回答 4

3

只需使用比较运算符(>、<、>=、<=、== 和 !=),因为它们是在 DateTime 中实现的。

例子:

DateTime lowerAllowedDate = new DateTime(1,1,1); // 01/01/0001
DateTime upperAllowedDate = new DateTime(3000, 12, 31) // 31/12/3000
DateTime now = DateTime.Now
if (lowerAllowedDate <= now && now < upperAllowedDate) 
{
   //Do something with the date at is in within range
} 
于 2011-06-19T15:55:11.777 回答
2

考虑这些扩展方法。

public static class ValidatedDateTimeOperations
{
  public static bool TrySubtract (this DateTime dateTime, TimeSpan span, out DateTime result)
  {
    if (span < TimeSpan.Zero)
       return TryAdd (dateTime, -span, out result);
    if (dateTime.Ticks >= span.Ticks)
    {
       result = dateTime - span;
       return true;
    }
    result = DateTime.MinValue;
    return false;
  }
  public static bool TryAdd (this DateTime dateTime, TimeSpan span, out DateTime result)
  {
    if (span < TimeSpan.Zero)
       return TrySubtract (dateTime, -span, out result);
    if (DateTime.MaxValue.Ticks - span.Ticks >= dateTime.Ticks)
    {
       result = dateTime + span;
       return true;
    }
    result = DateTime.MaxValue;
    return false;
  }
}

可以这样调用:

DateTime result;
if (DateTime.MinValue.TrySubtract (TimeSpan.FromDays(1), out result)
{
   // Subtraction succeeded.
}
于 2011-06-19T16:08:15.113 回答
1

事先检查给定操作中的溢出是很麻烦的,我不确定它是否真的值得简单地处理exception.

例如,您可以在减去时执行以下操作:

 DateTime date;
 TimeSpan subtractSpan;
 if ((date - DateTime.MinValue) < subtractSpan)
 {
      //out of range exception: date - subtractSpan
 }

值得?你的来电。

于 2011-06-19T16:00:39.230 回答
0

查看 MSDN 中的DateTime结构文档。

特别是,您可以查看:

  • TryParse 和 TryParseExact
  • 比较运算符
  • 最小值和最大值

您还可以将 try..catch (ArgumentOutOfRangeException) 放在您尝试使用的 DateTime 值周围。

但是,如果您一直(或曾经?)遇到这种异常,我会仔细研究您的设计。除非您正在做一些严肃的日期处理,否则我不知道有任何情况会遇到最小值和最大值。

于 2011-06-19T16:01:46.640 回答