Date类型的数据进行相加减等操作,下面给大家介绍一种比较常见通用的工具类操作Date类型的实现日期加减
思路:将Date类型转换为LocalDate类型,在使用LocalDate本身的API进行时间加减操作,最后转换为Date类型返回
public static void main(String[] args) {
Date date = new Date();
System.out.println("当前的日期为 = " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
// 1.转换为localDate类型
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// 2.日期相加减
// 添加1天 and 转换为Date日期格式输出
LocalDate addDayTime = localDate.plusDays(1);
Date addDay = Date.from(addDayTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
System.out.println("添加一天后的日期为 = " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(addDay));
// 添加1周 and 转换为Date日期格式输出
LocalDate addWeekTime = localDate.plusWeeks(1);
Date addWeek = Date.from(addWeekTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
System.out.println("添加一周后的日期为 = " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(addWeek));
// 添加1月 and 转换为Date日期格式输出
LocalDate addMouthTime = localDate.plusMonths(1);
Date addMouth = Date.from(addMouthTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
System.out.println("添加一个月的日期为 = " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(addMouth));
// 减少2天 and 转换为Date日期格式输出
LocalDate minusDayTime = localDate.minusDays(2);
Date minus2Day = Date.from(minusDayTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
System.out.println("减少两天的日期为 = " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(minus2Day));
}