Determining a calendar year (with/without leap-years)
UPDATE: The moral of the story is to trust a gut feeling and not to go looking for problems. In the end the user reported issue was in a completely different area and as Jon highlighted we introduced a bug in our testing, which we missed because the result appeared to validate what were looking for.
Original Question:
In many applications there is a requirement to display a start / end date, where the end date encompasses one calendar year. So if the start date is 1st Jan 2012, the end date is 31st Dec 2012. The basic rule is add a year, take a day off - as an extension method that you be:
public static DateTime CalendarYear(this DateTime dateTime)
{
return dateTime.AddYears(1).AddDays(-1);
}
开发者_高级运维
However, the code above does not cope with leap years! Our unit tests flagged up 365 occurences where the expected date date did not match the determined end date when testing from a start date of 1st Jan 2011 thru to 31st Dec 2014. The dates that define the error boundaries are:
- Start Date: 01 Mar 2011, Expected End Date: 28 Feb 2012: Actual End Date: 29 Feb 2012
- Start Date: 28 Feb 2012, Expected End Date: 26 Feb 2013: Actual End Date: 27 Feb 2013
Dates before 1st Mar 2011 behave as expected, those after 28th Feb 2012 behave as expected.
I know the reason that the tests are failing is because the start / end dates contain the 29th Feb leap year event, but does anyone have a simple, reliable suggestion (which copes with the leap year event) to replace the basic "AddYears(1).AddDays(-1)" to quickly determine a calendar year ?
It looks to me like the "actual" versions are correct... why would you expect "one year minus a day" from Feb 28th to be Feb 26th? How can you say that it encompasses a calendar year if Feb 27th isn't included anywhere?
If you really want those values, have you considered just calling AddDays(364)
instead?
I must be missing something real obvious as if I put in 1st March 2011, and do addyear-1day, I get as I as a human would expect 29th feb 2012, if I do 28th feb 2012 addyear-1day I get the 27th feb 2013.. if you just want to add 365 days, then do so. I am a little confused. So your actual ends look to be right.
More coffee required?
精彩评论