【问题标题】:DateTime algorithm suggestionDateTime算法建议
【发布时间】:2015-07-24 19:27:59
【问题描述】:

我的要求是根据另一个日期计算一个日期。 计算所需的一般规则是:

  1. 如果输入日期介于 4 月 1 日和 9 月 30 日(任何年份)之间,则计算结果应等于输入年份的 12 月 31 日
  2. 如果输入日期介于 10 月 1 日和 3 月 31 日之间,则计算结果应等于“下一个”6 月 30 日。

根据这些要求,我有这个代码:

DateTime tmpDate = new DateTime( 2000, inputDate.Month, inputDate.Day );
DateTime aprilDate = new DateTime( 2000, 4, 1 );
DateTime septemberDate = new DateTime( 2000, 9, 30 );
DateTime endofYearDate = new DateTime( 2000, 12, 31 );
DateTime resultDate = DateTime.MaxValue;

if ( tmpDate >= aprilDate && tmpDate <= septemberDate ) {
    resultDate = new DateTime( inputDate.Year, 12, 31, 23, 59, 59 );
}
else {
    if ( tmpDate > septemberDate && tmpDate <= endofYearDate ) {
        resultDate = new DateTime( inputDate.Year, 12, 31, 23, 59, 59 );
    }
    else {
        resultDate = new DateTime( inputDate.Year + 1, 12, 31, 23, 59, 59 );
    }
}

但是我认为这段代码有点乱。我怎样才能写得更好?

【问题讨论】:

  • 至少Code Review 会不会更好?
  • 嗯,不知道那个网站的存在。感谢分享

标签: c# datetime


【解决方案1】:

这看起来很复杂:

if ( inputDate.Month > 3 && inputDate.Month < 10 ) {
    resultDate = new DateTime( inputDate.Year, 12, 31, 23, 59, 59 );
}
else if (inputDate.Month > 9 ) {
    //June, per spec rather than OPs code
    resultDate = new DateTime( inputDate.Year + 1, 6, 30, 23, 59, 59 ); 
} else {
    //Ditto
    resultDate = new DateTime( inputDate.Year, 6, 30, 23, 59, 59 );
}

但是,这些价值观的时代存在确实让我担心。如果您打算使用这些值作为特定时期的终点,我建议您计算接下来的 7 月或 1 月 1 日,然后使用&lt; 比较而不是&lt;=。您犯错误的可能性要小得多,例如排除发生在 期间最后一秒内的事件。

【讨论】:

  • 嗯,你是对的时间。为了简单起见,我已经简化了这个问题。关于你发布的代码,那不是和我的完全一样吗?
  • @Lorenzo - 不,我不是为了比较 DateTimes 而在 2000 年构建大量额外的 DateTime 值 - 我只是比较输入月份值。
  • 哦,对了,谢谢。您认为可以审查此代码以使用 Timespan 的代码吗?
【解决方案2】:
DateTime delayedInputDate = inputDate.AddMonths(3);

if (delayedInputDate.Month < 7)
    resultDate = new DateTime(delayedInputDate.Year, 6, 30);
else
    resultDate = new DateTime(delayedInputDate.Year, 12, 31);

【讨论】:

  • 虽然从功能的角度来看这可能正确也可能不正确(我没有检查过),但我强烈建议反对这样的解决方案。清晰地传达意图(规范、业务规则)的代码应该优先于“聪明”的算法。
  • @nodots 总的来说,我同意你的看法。但是由于 OP 知道解决方案,并且仍然要求更好的解决方案,也许他要求一个有趣的解决方案。
  • @nodots 和Code that clearly communicates intent 是非常主观的。在问题中,海报试图解释问题。它需要很多句子。如果你轮班 3 个月,那么一切都会变得容易。我的目的不是给出一个解决方案,而是给出一个新的观点。
猜你喜欢
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 2011-04-13
  • 2018-12-20
  • 2019-11-08
  • 1970-01-01
  • 2015-10-06
相关资源
最近更新 更多