且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DateTime.AddYears在leap年的行为

更新时间:2023-11-29 12:50:04


我认为大多数人会认为从29.02.leapX开始的一年是01.03.leapX + 1。

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

我不会。我通常会期望截断。从根本上讲,这类似于在1月30日之前增加一个月-我希望在2月的最后一天。在这两种情况下,您都添加了一个较大的单位(月或年),而一个较小的单位(天)被截断以适应年/月组合。

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.

Joda时间 Noda Time 也表现得不错,顺便说一句。)

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

正如Tim在评论中提到的,它是也以这种方式记录

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


AddYears方法考虑leap年,计算得出的年份。生成的DateTime对象的月份和时间部分与此实例相同。

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.

因此 month 必须保持为2月;显然,年份会根据添加的年份而变化-因此必须调整日期以保持有效。

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.