java8新特性日期時間API

在Java8以前,關於日期時間處理的API( java.util.Date 、java.util.Calendar、java.util.TimeZone、java.sql)有很多不理想的地方,如:

  • 非線程安全
  • 設計很差
  • 時區處理麻煩

但新的日期時間API中,做了很好的優化,這些類都位於java.time包下,其中有兩個比較重要的API:

  • Local(本地) − 簡化了日期時間的處理,沒有時區的問題。
  • Zoned(時區) − 通過制定的時區處理日期時間。

本地相關API

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalUnit;

public class NewDateTimeTest {
    public static void main(String[] args) {
        //日期類
        LocalDate now = LocalDate.now();
        System.out.println("當前日期爲:" + now);
        //比較兩個日期大小
        System.out.println("當前日期在在2020年12月12日後?->"+now.isAfter(LocalDate.of(2020,12,12)));//當前日期在在2020年12月12日後?->false

        //時間類
        LocalTime localTime = LocalTime.now();
        System.out.println("當前時間爲:" + localTime);

        //日期時間類
        LocalDateTime localDateTime = LocalDateTime.now();
        //格式化輸出
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH時mm分ss秒");
        System.out.println("當前日期時間爲:" + localDateTime.format(dateTimeFormatter)); //當前日期時間爲:2019年11月18日 15時24分42秒


        //Duration類,用於計算兩個LocalTime或兩個LocalDateTime的時間差,
        Duration between = Duration.between(LocalTime.now(), LocalTime.of(22, 10, 55));
        System.out.println("兩個時間相差:" + between.getSeconds() + "秒");

        //Period類用於計算兩個LocalDate之間的時間差
        Period between1 = Period.between(LocalDate.of(2019, 11, 11), LocalDate.of(2020, 12, 12));
        System.out.println("兩個日期相差:" + between1.getYears() + "年" + between1.getMonths() + "月" + between1.getDays() + "天"); //兩個日期相差:1年1月1天

        //MonthDay類只包含月日信息,可用於存放生日,紀戀日等信息。
        LocalDate birthday = LocalDate.of(1999, 11, 18);
        MonthDay monthDay = MonthDay.from(birthday);
        System.out.println("今天是我的生日嗎?:"+monthDay.equals(MonthDay.now()));

    }
}

在此只是列出了一些類的少許方法,比如像日期時間加減比較操作、獲取特定字段信息也是有相關方法的,大家自己用的時候去嘗試吧。

時區API

import java.time.ZonedDateTime;
import java.time.ZoneId;

public class Java8Tester {
   public static void main(String args[]){
      Java8Tester java8tester = new Java8Tester();
      java8tester.testZonedDateTime();
   }
       
   public void testZonedDateTime(){
       
      // 獲取當前時間日期
      ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
      System.out.println("date1: " + date1);
               
      ZoneId id = ZoneId.of("Europe/Paris");
      System.out.println("ZoneId: " + id);
               
      ZoneId currentZone = ZoneId.systemDefault();
      System.out.println("當期時區: " + currentZone);
   }
}

參考鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章