开发者

C# - calculate if a date is six months older

I am trying to calculate if the given specified date is at least six months old. I am doing this:

if(DateTime.Now.AddMonths(-6)>date)
{
    //Do something
}

Is this correct?

Some people say that this approach is wrong and will not give accurate results. Is the above is corre开发者_高级运维ct?


"6 months" is not a precise amount of time. It depends on the length of the months. In particular, you may well get different results from your calculation compared with date.AddMonths(6) < DateTime.Now. (Consider adding 6 months from August 30th vs taking away 6 months from February 28th... You may be okay, but you need to think about this carefully.)

You need to consider a few things carefully:

  • You're currently using DateTime.Now instead of DateTime.Today; how do you want the current time of day to affect things?
  • Is the "kind" of date UTC, unspecified or local? It makes a difference - DateTime is confusing, unfortunately.
  • How do you want to handle situations like the ones in the first paragraph?

Ultimately, if people are telling you it will not give accurate results, you should ask them for specific examples - you need to get a wealth of input data and desired results, add automated tests for them, and get them to pass. Then if anyone claims your code isn't working correctly, you should be able to challenge them to create another test case which fails, and justify their decision.


If you are only concerned about the date and not the time, use DateTime.Now.Date instead. Apart from that, I do not see any problems with the code you already have.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜