jdk8中日期和時間api的使用
阿新 • • 發佈:2020-11-27
jdk8之前的日期和時間api非常難用,在jdk8中對其進行了很大的優化,並且此次優化將在今後一段時間內不再變更,所以相當重要。
之前的相關類主要有Date,Calender,SimpleDateFormat
在jdk8中提供了新的類LocalDateTime,Instant,DateTimeFormatter,我們可以使用新的類來替換原有的類實現同樣的功能。
package com.atguigu.date; import org.junit.Test; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; public class JDK8DateTimeTest { /** * LocalDate LocalTime LocalDateTime 的使用 */ @Test public void test1() { // 當前時間 LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDate); System.out.println(localTime); System.out.println(localDateTime); // 建立指定年月日時分秒的時間 LocalDateTime localDateTime1 = LocalDateTime.of(2020, 11, 27, 8, 55); System.out.println(localDateTime1); // getXxx() 獲取相關的屬性 /*System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getDayOfWeek()); System.out.println(localDateTime.getMonth()); System.out.println(localDateTime.getMonthValue());*/ // withXxx() 可理解為 設定相關的屬性 // 體現不可變性 通過設定返回一個新的時間,原來的時間不變 LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(20); System.out.println(localDateTime); System.out.println(localDateTime2); LocalDateTime localDateTime3 = localDateTime.withHour(4); System.out.println(localDateTime3); // 加減 // 不可變性 LocalDateTime localDateTime4 = localDateTime.plusHours(8); System.out.println(localDateTime4); System.out.println(localDate); LocalDateTime localDateTime5 = localDateTime.minusMonths(4); System.out.println(localDateTime5); System.out.println(localDateTime); } /** * Instant的使用 * 瞬時 */ @Test public void test2() { // 例項化 Instant instant = Instant.now(); System.out.println(instant); // 本初子午線所對應的時間 OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime); // 獲取離1970.1.1的毫秒數 long milli = instant.toEpochMilli(); System.out.println(milli); // 通過離1970.1.1的毫秒數來例項化 Instant instant1 = Instant.ofEpochMilli(1606441584674L); System.out.println(instant1); } /** * DateTimeFormatter的使用:格式化、解析 日期時間 * 格式化:把日期轉化為日期格式的字串 * 解析:格式化的逆過程,把日期格式的字串轉化為日期 */ @Test public void test3() { // 例項化 //1 標註格式的formatter //2 本地格式的formatter //3 自定義格式的formatter // 主要用第三種 自定義格式 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); // 格式化 String str = dateTimeFormatter.format(LocalDateTime.now()); System.out.println(str);//2020-11-27 10:22:26 // 解析 TemporalAccessor parse = dateTimeFormatter.parse("2020-11-27 10:21:26"); System.out.println(parse); } }