java怎么计算上一个月_在java.time中,添加一个月的结果如何计算?

简答:

在这个例子中,结果将是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来打包你的特殊逻辑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值