简答:
在这个例子中,结果将是2012-02-29的最后一天。
说明:
这个问题,“如果你添加一个月,你会得到什么日期”,这是可以解释的。为避免这种情况,java.time API有一个clear rule.结果将与输入的月份相同,除非这是无效的日期,否则结果是该月的最后一天。
因此,1月31日加上一个月将导致2月31日,但由于这是无效的日期,结果是2月28日或29日的最后一个有效日期,取决于是闰年:
// normal case
2011-01-15 plus 1 month = 2011-02-15 // 15 Jan -> 15 Feb
// special rule choosing the last valid day-of-month
2011-01-31 plus 1 month = 2011-02-28 // 31 Jan -> 28 Feb (2011 is normal year)
2012-01-31 plus 1 month = 2012-02-29 // 31 Jan -> 29 Feb (2012 is leap year)
// same rule applies for months other than February
2013-03-31 plus 1 month = 2013-04-30 // 31 Mar -> 30 Apr (only 30 days in April)
无论添加一个月还是几个月,并且始终基于生成的月份,同样的规则适用。即。该月首先添加(如果需要调整年份),那么只有当天的考虑。相同的规则也适用于减法。
// multiple months works on the month of the result
2013-10-31 plus 4 months = 2014-02-28 // last day of February
2013-10-31 minus 4 months = 2013-06-30 // last day of June
相同的规则也适用于在/从日期添加/减去年份 – 添加年份后,只有当月的日期检查有效期。
// years use the same rule
2012-02-29 plus 1 year = 2013-02-28 // 29th February invalid so adjusted to 28th
如果您的业务逻辑需要一个不同的月份规则,最好的方法是编写一个TemporalAdjuster或TemporalAmount来打包你的特殊逻辑。