有一个常见日期操作计算两个日期之间的年数、月数、天数。在Java 8中可以用java.time.Period类来做计算。
import java.time.LocalDate;
import java.time.Period;
public class DateUtil {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
// 当前日期: 2022-01-21
System.out.println("当前日期: "+today);
LocalDate oldDate = LocalDate.of(2018, 6, 28);
Period period = Period.between(today, oldDate);
String resule = new StringBuilder()
.append(period.getYears()).append("年")
.append(period.getMonths()).append("月")
.append(period.getDays()).append("天").toString()
.replace("-","");
// 3年6月23天
System.out.println(resule);
}
}