Date日期类型相加减操作(超详细)

前言
Date类型的时间操作我们在日常开发中经常使用,也会经常使用Date类型的数据进行相加减等操作,下面给大家介绍一种比较常见通用的工具类操作Date类型的实现日期加减

思想
将Date类型转换为LocalDate类型,在使用LocalDate本身的API进行时间加减操作,最后转换为Date类型返回

 
    /**
     * ps:为了直观,将Date类型转换为字符串打印
     *
     * @param args
     */
    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));
 
    }

猜你喜欢

转载自blog.csdn.net/qq_44543774/article/details/131655212