Date date type addition and subtraction operation (super detailed)

Foreword
Date type time operations are often used in daily development, and also often use Date type data for addition and subtraction operations. Let me introduce a more common and general tool operation Date type to achieve date addition and subtraction

Idea
Convert Date type to LocalDate type, use LocalDate's own API to perform time addition and subtraction operations, and finally convert to Date type to return

 
    /**
     * 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));
 
    }

Guess you like

Origin blog.csdn.net/qq_44543774/article/details/131655212