How JDK 8 uses LocalDate to calculate the number of days between two dates

How JDK 8 uses LocalDate to calculate the number of days between two dates

JDK 8 provides a new class date LocalDate, through LocalDateeasy to operate date, will often need to calculate the number of days between two dates in the actual development process.

1. Get the total date interval

// 指定转换格式
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");

LocalDate startDate = LocalDate.parse("2019-03-01",fmt);
LocalDate endDate = LocalDate.parse("2020-04-02",fmt);

System.out.println("总相差的天数:" + startDate.until(endDate, ChronoUnit.DAYS));
System.out.println("总相差的月数:" + startDate.until(endDate, ChronoUnit.MONTHS));
System.out.println("总相差的年数:" + startDate.until(endDate, ChronoUnit.YEARS));

Output result:

总相差的天数:398
总相差的月数:13
总相差的年数:1

2. Get separate date intervals for year, month, and day

Use LocalDateown until()method of calculating the difference between the total number of years, months and days, if you want to calculate the date necessary to use a separate Periodclass, such as the above 2019-03-01and 2020-04-02date difference: 1 年 1 个月 1 天the relevant code is as follows:

//指定转换格式
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");

LocalDate startDate = LocalDate.parse("2019-03-01", fmt);
LocalDate endDate = LocalDate.parse("2020-04-02", fmt);

Period period = Period.between(startDate, endDate);
System.out.println("相差:" + period.getYears() + " 年 " + period.getMonths() + " 个月 "
	 + period.getDays() + " 天");

Output result:

相差:11 个月 1

3. Matters needing attention

In actual use, the two cases should be distinguished, otherwise problems will occur.

Roc’s Blog.

Guess you like

Origin blog.csdn.net/peng2hui1314/article/details/106495095