Java的日期API一直被诟病,在Java 8中引入了新的日期API。包括: LocalData, LocalTime, LocalDateTime, Clock, Instant 等 ### 日期格式化 1. 方式1 ``` SimpleDateFormat dateFm = new SimpleDateFormat("yyyy/MM/dd"); String dateStr = dateFm.format(new Date()); System.out.println(dateStr); ``` 2. 方式2: Java 8 开始支持 ``` DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); //java 8 dateStr = formatter.format(LocalDate.now()); System.out.println(dateStr); ``` ### 获取年月日,时分秒 使用java.util.Calendar, 在java 8可以使用 java.time.LocalDateTimel。 ``` Calendar cal = Calendar.getInstance(); System.out.println(cal.get(Calendar.YEAR)); //2022 System.out.println(cal.get(Calendar.MONDAY)); //0-11 System.out.println(cal.get(Calendar.DATE)); // System.out.println(cal.get(Calendar.HOUR_OF_DAY)); System.out.println(cal.get(Calendar.MINUTE)); System.out.println(cal.get(Calendar.SECOND)); ``` ``` LocalDateTime dt = LocalDateTime.now(); System.out.println(dt.getYear()); System.out.println(dt.getMonthValue());// 1-12 System.out.println(dt.getDayOfMonth()); System.out.println(dt.getHour()); System.out.println(dt.getMinute()); System.out.println(dt.getSecond()); ``` * Calendar 的月份是从0 开始, 到11; LocalDateTime 的月份是从1 开始,到12 ### 获取毫秒 最起码有三种方式: 1. System ``` mills = System.currentTimeMillis(); System.out.println(mills); ``` 2. Calendar ``` long mills = Calendar.getInstance().getTimeInMillis(); System.out.println(mills); ``` 3. 方式3: 从Clock获取(Java 8开始支持) ``` mills = Clock.systemDefaultZone().millis();//Java 8 System.out.println(mills); ``` ### 获取昨天的这个时间 ``` Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); System.out.println(cal.getTime()); ``` 在日历上减去一天 Java 8 ,写法可以如下: ``` LocalDateTime today = LocalDateTime.now(); LocalDateTime yesterday = today.minusDays(-1); System.out.println(yesterday); ``` ## 日期运算 ``` ~~~ Calendar ~~~ ```