Java8 日期和時間API

LocalDate、LocalTime、Instant、Duration、Period

1.1使用LocalDate和LocalTime

1.1.1LocalDate的建立方式和相關方法使用示例

@Test
        public void localDate() {
        LocalDate date = LocalDate.of(2019, 11, 1);
        int year = date.getYear();// 2019
        Month month = date.getMonth();// NOVEMBER
        int day = date.getDayOfMonth();// 1
        DayOfWeek dow = date.getDayOfWeek();// FRIDAY
        int len = date.lengthOfMonth();// 30
        boolean leap = date.isLeapYear();// false
        System.out.println(year + ", " + month + ", " + day + ", " + dow + ", " + len + ", " + leap);

        LocalDate date2 = LocalDate.now();
        int year2 = date2.get(ChronoField.YEAR);//2019
        int month2 = date2.get(ChronoField.MONTH_OF_YEAR);// 12
        int day2 = date2.get(ChronoField.DAY_OF_MONTH);// 14
        int dow2 = date2.get(ChronoField.DAY_OF_WEEK);//  6
        System.out.println(year2 + ", " + month2 + ", " + day2 + ", " + dow2);
		
        //不能夠寫成2019-11-1 會報DateTimeParseException
        LocalDate date3 = LocalDate.parse("2019-11-01");
        int year3 = date3.get(ChronoField.YEAR);//2019
        int month3 = date3.get(ChronoField.MONTH_OF_YEAR);// 11
        int day3 = date3.get(ChronoField.DAY_OF_MONTH);// 1
        int dow3 = date3.get(ChronoField.DAY_OF_WEEK);// 5
        System.out.println(year3 + ", " + month3 + ", " + day3 + ", " + dow3);
    }

1.1.1LocalTime對象的建立方式以及相關方法示例

@Test
    public void localTime() {
        LocalTime time = LocalTime.of(11, 06, 23);
        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();
        System.out.println(hour + ":" + minute + ":" + second);//  11:6:23

        LocalTime time2 = LocalTime.now();
        int hour2 = time2.get(ChronoField.HOUR_OF_DAY);
        int minute2 = time2.get(ChronoField.MINUTE_OF_HOUR);
        int second2 = time2.get(ChronoField.SECOND_OF_MINUTE);
        System.out.println(hour2 + ":" + minute2 + ":" + second2);//當前時間

        // 寫13:9:22會報錯,DateTimeParseException異常,能夠傳一個DateTimeFormatter自定義格式
        LocalTime time3 = LocalTime.parse("13:09:22");
        int hour3 = time3.get(ChronoField.HOUR_OF_DAY);
        int minute3 = time3.get(ChronoField.MINUTE_OF_HOUR);
        int second3 = time3.get(ChronoField.SECOND_OF_MINUTE);
        System.out.println(hour3 + ":" + minute3 + ":" + second3);// 13:9:22
    }

1.1.3LocalDateTime對象3種建立方式以及相關方法示例

Test
    public void localDateTime() {
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
 
        // 建立LocalDateTime
        LocalDateTime dateTime = LocalDateTime.of(2019, 11, 1, 13, 32, 28);
        LocalDateTime dateTime2 = LocalDateTime.of(date, time);
        LocalDateTime dateTime3 = date.atTime(13, 32, 28);
        LocalDateTime dateTime4 = date.atTime(time);
        LocalDateTime dateTime6 = time.atDate(date);
 
        // 轉化
        LocalDate date2 = dateTime2.toLocalDate();
        LocalTime time2 = dateTime2.toLocalTime();
    }

1.1.4 機器的日期和時間格式

你能夠經過向靜態工廠方法ofEpochSecond傳遞一個表明秒數的值建立一個該類的實例。靜態工廠方法ofEpochSecond還有一個加強的重載版本,它接收第二個以納秒爲單位的參數值,對傳入做爲秒數的參數進行調整。重載的版本會調整納秒參數,確保保存的納秒分片在0到999 999999之間。這意味着下面這些對ofEpochSecond工廠方法的調用會返回幾乎一樣的Instant對象:java

Instant.ofEpochSecond(3);
Instant.ofEpochSecond(3, 0);
// 2 秒以後再加上100萬納秒(1秒)
Instant.ofEpochSecond(2, 1_000_000_000);
// 4秒以前的100萬納秒(1秒)
Instant.ofEpochSecond(4, -1_000_000_000);

正如你已經在LocalDate及其餘爲便於閱讀而設計的日期-時間類中所看到的那樣,Instant類也支持靜態工廠方法now,它可以幫你獲取當前時刻的時間戳。咱們想要特別強調一點,Instant的設計初衷是爲了便於機器使用。它包含的是由秒及納秒所構成的數字。因此,它沒法處理那些咱們很是容易理解的時間單位。好比下面這段語句:安全

int day = Instant.now().get(ChronoField.DAY_OF_MONTH);

它會拋出下面這樣的異常:spa

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth

你能夠經過Duration和Period類使用Instant線程

1.1.5 定義Duration和Period(時間間隔對象)

  • Duration:能夠傳2個localTime對象,localDateTime對象或者Instant對象
  • Period:用年,月,日建模,能夠傳2個localDate對象
Duration d1 = Duration.between(time1, time2);
Duration d2 = Duration.between(dateTime1, dateTime2);
Duration d3 = Duration.between(instant1, instant2);

由 於LocalDateTime和Instant是爲不一樣的目的而設計的,一個是爲了便於人閱讀使用,另外一個是爲了便於機器處理,因此你不能將兩者混用。若是你試圖在這兩類對象之間建立duration,會觸發一個DateTimeException異常 。 若是你須要以年、月或者日的方式對多個時間單位建模,可使用Period類。使用該類的工廠方法between,你可使用獲得兩個LocalDate之間的時長,以下所示 :設計

Period period = Period.between(LocalDate.of(2019, 11, 07), LocalDate.of(2019, 11, 07));

Duration和Period類都提供了不少很是方便的工廠類,直接建立對應的實例;換句話說,就像下面這段代碼那樣,再也不是隻能以兩個temporal對象的差值的方式來定義它們的對象。code

Duration threeMinutes = Duration.ofMinutes(3);
Duration fourMinutes = Duration.of(4, ChronoUnit.MINUTES);

Period tenDay = Period.ofDays(10);
Period threeWeeks = Period.ofWeeks(3);
Period twoYearsSixMonthsOneDay = Period.of(2, 6, 1);

1.2 操縱 解析和格式化日期

1.2.1

  • 以比較直觀的方式操縱LocalDate的屬性

下面的這段代碼中全部的方法都返回一個修改了屬性的對象。它們都不會修改原來的對象!orm

LocalDate date1 = LocalDate.of(2019, 11, 1);//2019-11-01
LocalDate date2 = date1.withYear(2020);//2020-11-01
LocalDate date3 = date2.withDayOfMonth(25);//2020-11-25
LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 9);//2020-09-25
  • 以相對方式修改LocalDate的屬性
@Test
public void editDateTime() {
        LocalDate date1 = LocalDate.of(2019, 11, 01);// 2019-11-01
        LocalDate date2 = date1.plusWeeks(1);// 2019-11-08
        LocalDate date3 = date2.minusYears(2);// 2017-11-08
        LocalDate date4 = date3.plus(6, ChronoUnit.MONTHS);// 2018-05-08
    }

1.2.3 TemporalAdjuster

@Test
public void adjust() {
        LocalDate date1 = LocalDate.of(2019, 11, 01);// 2019-11-01
        LocalDate date2 = date1.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));// 2019-11-03
        LocalDate date3 = date2.with(TemporalAdjusters.lastDayOfMonth());// 2019-11-30
    }

TemporalAdjuster類的工廠方法對象

1.2.4自定義格式化輸出日期

新版本,咱們擁有一個線程安全的類:DateTimeFormatter 來看代碼blog

@Test
    public void formatPrint() {
        LocalDate date = LocalDate.of(2019, 11, 01);
        String s1 = date.format(DateTimeFormatter.BASIC_ISO_DATE);// 20191101
        String s2 = date.format(DateTimeFormatter.ISO_LOCAL_DATE);// 2019-11-01

        LocalDate date1 = LocalDate.parse("20191101", DateTimeFormatter.BASIC_ISO_DATE);
        LocalDate date2 = LocalDate.parse("2019-11-01", DateTimeFormatter.ISO_LOCAL_DATE);

        // 自定義格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        String formattedDate = date.format(formatter);
        System.out.println(formattedDate);// 01/11/2019
        LocalDate date3 = LocalDate.parse(formattedDate, formatter);

        // 帶時區的日期(本地化)
        DateTimeFormatter italianFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy", Locale.ITALIAN);
        String formattedDate2 = date.format(italianFormatter); 
        LocalDate date4 = LocalDate.parse(formattedDate2, italianFormatter);
    }
相關文章
相關標籤/搜索