使用Period.between方法
SimpleDateFormat formatter = new SimpleDateFormat(BaseConstants.Pattern.DATETIME);
ParsePosition pos = new ParsePosition(0);
Date date1 = formatter.parse("2021-11-16 17:50:54", pos);
ParsePosition pos2 = new ParsePosition(0);
Date date2 = formatter.parse("2027-01-06 06:50:54", pos2);
//将Date类型转化为LocalDate
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = date1.toInstant();
LocalDate localDate1 = instant.atZone(zoneId).toLocalDate();
Instant instant2 = date2.toInstant();
LocalDate localDate2 = instant2.atZone(zoneId).toLocalDate();
Period period = Period.between(localDate1, localDate2);
StringBuffer sb = new StringBuffer();
System.out.println("相差年份:"+period.getYears());
System.out.println("相差月份:"+period.getMonths());
System.out.println("相差天数:"+period.getDays());
打印结果:
相差年份:5
相差月份:1
相差天数:21
不能使用通过DateFormat.getDateInstance()方法将Date转为LocalDate的原因为:
String strDate1= DateFormat.getDateInstance().format(date1);
String strDate2 = DateFormat.getDateInstance().format(date2);
System.out.println("strDate1:"+strDate1);
System.out.println("strDate2:"+strDate2);
LocalDate Ldate1 = LocalDate.parse(strDate1);
LocalDate Ldate2 = LocalDate.parse(strDate2);
打印结果:
strDate1:2021-11-16
strDate2:2027-1-6
报错:Text ‘2027-1-6’ could not be parsed at index 5