import java.time.LocalDate; import java.time.Period; import java.time.temporal.TemporalAdjusters; public class DateUtils { //日期转字符串 public static String dateStr(LocalDate date){ return date.toString(); } /** * 字符串转时间 * @param t "2021-03-03" * @return */ public static LocalDate parse(String t) { return LocalDate.parse(t); } /** * 时间计算 * @param date 不传则默认今天 * @param day * @return */ public static LocalDate calcDate(LocalDate date, int day) { return date.plusDays(day); } public static LocalDate calcDate(int day) { return LocalDate.now().plusDays(day); } /** * 计算两个日期之间相隔几天 * @param before 开始 "2021-03-03" * @param after 结束 "2021-03-10" * @return 7 */ public static Integer duration(LocalDate before, LocalDate after){ return Period.between(before, after).getDays(); } /** * 获取指定月最后一天 * @param date 不传默认当月 * @return */ public static LocalDate getLastDayOfMonth(LocalDate date){ return date.with(TemporalAdjusters.lastDayOfMonth()); } public static LocalDate getLastDayOfMonth(){ return LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()); } /** * 获取指定月第一天 * @param date 不传默认当月 * @return */ public static LocalDate getFirstDayOfMonth(LocalDate date){ return date.with(TemporalAdjusters.firstDayOfMonth()); } public static LocalDate getFirstDayOfMonth(){ return LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); } public static void main(String[] args) { LocalDate now = LocalDate.now(); System.out.println(now.toEpochDay()); System.out.println(DateUtils.duration(DateUtils.parse("2021-03-13"),DateUtils.parse("2021-03-10"))); } }