Behavior of DateTime.AddYears on leap year

I think most people would assume that "one year from 29.02.leapX is 01.03.leapX+1".

I wouldn't. I would normally expect truncation. It's fundamentally similar to adding one month to January 30th - I'd expect to get the last day in February. In both cases, you're adding a "larger unit" (month or year) and a "smaller unit" (day) is being truncated to fit in with the year/month combination.

(This is how Joda Time and Noda Time behave too, btw.)

As Tim mentioned in comments, it's documented that way too:

The AddYears method calculates the resulting year taking into account leap years. The month and time-of-day part of the resulting DateTime object remains the same as this instance.

So the month has to stay as February; the year will change based on how many years are being added, obviously - so the day has to adjust to stay valid.


With your rationale then 1-Mar-2012 would become 2-Mar-2012 when you added a year. If you add this shift for all prior leap years then you are going to find your calculation massively adrift. The only sensible response is to return 28-Feb for non-leap years.

Tags:

C#

.Net

Datetime