Java 8中的日期时间API是考虑了闰年和平年的特残情况的。在这个API中,LocalDate
类表示日期,ChronoUnit.DAYS.between()
方法计算两个日期之间的天数差异时会考虑闰年和平年的影响。
import java.time.LocalDate; import java.time.temporal.ChronoUnit; /** * @author XiSoil */ public class Test1DateCalculator { public static void main(String[] args) { String date1 = "2021-01-01"; String date2 = "2022-12-31"; LocalDate start = LocalDate.parse(date1); LocalDate end = LocalDate.parse(date2); long daysBetween = ChronoUnit.DAYS.between(start, end); System.out.println("Days between " + date1 + " and " + date2 + " : " + daysBetween); } }
通过计算获取相差天数
/** * @author XiSoil */ public class Test2DaysBetween { public static void main(String[] args) { System.out.println(daysBetween("2019-01-01", "2020-12-31")); } public static int daysBetween(String date1, String date2) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = null; Date d2 = null; try { d1 = sdf.parse(date1); d2 = sdf.parse(date2); } catch (Exception e) { e.printStackTrace(); } long between = (d2.getTime() - d1.getTime()) / (1000 * 3600 * 24); return Integer.parseInt(String.valueOf(between)) >= 0 ? Integer.parseInt(String.valueOf(between)) : -Integer.parseInt(String.valueOf(between)); } }
标签:date1,date2,String,MM,dd,yyyy,between,LocalDate,public From: https://www.cnblogs.com/xxaxf/p/18128835