java 计算相差几个月_Java 如何计算两个日期相差几个月零几天?

按照我的理解,2018-04-01 和 2018-08-02 应该是相差 4 个月零 1 天。

然后这是按照我的理解写出来的代码(基于 Java8):

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

public class DateDiff {

static int[] getDiff(LocalDate start, LocalDate end) {

if (!start.isBefore(end)) {

throw new IllegalArgumentException("Start must not be before end.");

}

int year1 = start.getYear();

int month1 = start.getMonthValue();

int day1 = start.getDayOfMonth();

int year2 = end.getYear();

int month2 = end.getMonthValue();

int day2 = end.getDayOfMonth();

int yearDiff = year2 - year1; // yearDiff >= 0

int monthDiff = month2 - month1;

int dayDiff = day2 - day1;

if (dayDiff < 0) {

LocalDate endMinusOneMonth = end.minusMonths(1); // end 的上一个月

int monthDays = endMinusOneMonth.lengthOfMonth(); // 该月的天数

dayDiff += monthDays; // 用上一个月的天数补上这个月差掉的日子

if (monthDiff > 0) { // eg. start is 2018-04-03, end is 2018-08-01

monthDiff--;

} else { // eg. start is 2018-04-03, end is 2019-02-01

monthDiff += 11;

yearDiff--;

}

}

int[] diff = new int[2];

diff[0] = yearDiff * 12 + monthDiff;

diff[1] = dayDiff;

return diff;

}

public static void main(String[] args) {

LocalDate startDate = LocalDate.of(2018, 4, 3);

LocalDate[] endDates = {

LocalDate.of(2018, 4, 5),

LocalDate.of(2018, 10, 6),

LocalDate.of(2019, 4, 5),

LocalDate.of(2019, 10, 6),

LocalDate.of(2019, 3, 3),

LocalDate.of(2019, 3, 1),

LocalDate.of(2019, 2, 1),

LocalDate.of(2019, 2, 2),

};

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

for (LocalDate end : endDates) {

int[] diff = getDiff(startDate, end);

System.out.printf("%s - %s = %2d 个月零 %-2d 天\n",

formatter.format(end), formatter.format(startDate), diff[0], diff[1]);

}

}

}

运行结果:

2c55fd231aa7fb08b8770151316c0552.png

刚发现原来 Java8 已经提供了解决这个问题 API,所以 getDiff 方法可以简化为:

static int[] getDiff(LocalDate start, LocalDate end) {

if (!start.isBefore(end)) {

throw new IllegalArgumentException("Start must not be before end.");

}

Period period = Period.between(start, end);

int years = period.getYears();

int months = period.getMonths();

int days = period.getDays();

return new int[] {years * 12 + months, days};

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值