Operación de suma y resta de tipo de fecha de fecha (super detallada)

Prólogo
Las operaciones de tiempo de tipo fecha se usan a menudo en el desarrollo diario, y también suelen usar datos de tipo fecha para operaciones de suma y resta Permítanme presentarles una operación de herramienta más común y general Tipo de fecha para lograr sumas y restas de fechas

Idea
Convierta el tipo de fecha en tipo LocalDate, use la propia API de LocalDate para realizar operaciones de suma y resta de tiempo y, finalmente, convierta el tipo de fecha para regresar

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

Supongo que te gusta

Origin blog.csdn.net/qq_44543774/article/details/131655212
Recomendado
Clasificación