java 8 比较日期核心 api
ChronoUnit
可比较 年、月、周、日、时、分、秒、毫秒、微秒、纳秒
java">import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;public class DateUtil {public static void main(String[] args) {// 格式一String startDate = "2024-01-01";Temporal startTemporal = LocalDate.parse(startDate);String endDate = "2024-10-01";Temporal endTemporal = LocalDate.parse(endDate);// 相差年long betweenYear = ChronoUnit.YEARS.between(startTemporal, endTemporal);// 相差月long betweenMonth = ChronoUnit.MONTHS.between(startTemporal, endTemporal);// 相差天long betweenDay = ChronoUnit.DAYS.between(startTemporal, endTemporal);// 格式二LocalDate beforeDate = LocalDate.of(2023, 9, 18);LocalDate afterDate = LocalDate.of(2024, 10, 8);//月数long betweenMonths = ChronoUnit.MONTHS.between(beforeDate, afterDate);//年数long betweenYears = ChronoUnit.YEARS.between(beforeDate, afterDate);//天数long betweenDays = ChronoUnit.DAYS.between(beforeDate, afterDate);// 相差时分LocalDateTime beforeTime = LocalDateTime.of(2024, 9, 19, 8, 0, 0);LocalDateTime afterTime = LocalDateTime.of(2024, 9, 19, 18, 0, 0);long betweenHours = ChronoUnit.HOURS.between(beforeTime, afterTime);long betweenMinutes = ChronoUnit.MINUTES.between(beforeTime, afterTime);}}