jdk8中的時間工具類
阿新 • • 發佈:2022-03-01
1. 以前日期時間類的問題
2. JDK8獲取時間物件
LocalDate(年月日) LocatTime(時分秒) LocatDateTime(年月日時分秒) public static LocalDateTime now() : 當前時間的日期時間物件 public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second)
- 程式碼
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 time = LocalDateTime.of(2008, 8, 8, 20, 0, 0); System.out.println(time);
3. JDK8獲取時間中的每一個值
// 獲取當前時間的LocalDateTime LocalDateTime now = LocalDateTime.now(); // 獲取年月日時分秒 int year = now.getYear(); int month = now.getMonthValue(); int dayOfMonth = now.getDayOfMonth(); int hour = now.getHour(); int minute = now.getMinute(); int second = now.getSecond(); System.out.println(year + "-" + month + "-" + dayOfMonth + "-" + hour + "-" + minute + "-" + second);
4. JDK8對時間屬性的加減和修改
public LocalDateTime withYear(int year) : 修改年
public LocalDateTime plusYears(long years) : 增加年
public LocalDateTime minusYears(long years) : 減少年
// 這類方法的返回值是LocalDateTime
// 在方法的內部修改屬性值, 將修改之後的結果(LocalDateTime型別), 返回回來
5. JDK8格式化和解析
DateTimeFormatter 的獲取方式:
public static DateTimeFormatter ofPattern(String pattern)
: pattern(模版)-> yyyy-MM-dd HH:mm:ss
public String format(DateTimeFormatter formatter) : 將LocatDateTime轉換成String (格式化)
public static LocalDateTime parse(CharSequence text,//CharSequence:String它爹,當成String
DateTimeFormatter formatter)
將字串, 轉換成LocalDateTime
6. JDK8時間間隔
- Duration
public static Duration between(Temporal startInclusive, // LocalDateTime型別
Temporal endExclusive) // LocalDateTime型別
Duration:
public long getSeconds() : 獲取相差的秒數
public int getNano() : 獲取相差的納秒
- Period
public static Period between(LocalDate startDateInclusive,
LocalDate endDateExclusive)
Period:
public int getYears()
public int getMonths()
public int getDays()
千里之行,始於足下。不積跬步,無以至千里