【JAVA8新的時間與日期 API】- 本地時間、時間戳、日期時間的操縱、解析和格式化、時區、與傳統日期的轉換

LocalDate、 LocalTime、 LocalDateTime

LocalDate、 LocalTime、 LocalDateTime 類的實例是 不可變對象 ,分表表示使用 ISO-8601 日曆系統的日期、時間、日期和時間。他們提供了簡單的日期或時間,並不包含當前的時間信息。也不包含與時區相關的信息。java

注:ISO-8601 日曆系統是國際標準化組織制定的現代公民的日期和時間的表示法。說白了就是全球統一標準的表示方法。ui

 

 示例1:

import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class TestLocalDateTime {
    @Test
    public void test1(){
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);//輸出:2020-06-25
        LocalTime localTime = LocalTime.now();
        System.out.println(localTime);//輸出:23:12:59.211
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);//輸出:2020-06-25T23:12:59.211
        System.out.println("-------------------------------------------");
        localDate = LocalDate.of(2022,1,1);
        System.out.println(localDate);//輸出:2022-01-01
        localDate = LocalDate.of(2023, Month.AUGUST,2);
        System.out.println("-------------------------------------------");
        System.out.println(localDate);//輸出:2023-08-02
        localTime = LocalTime.of(1,2);
        System.out.println(localTime);//輸出:01:02
        localTime = LocalTime.of(1,2,3);
        System.out.println(localTime);//輸出:01:02:03
        localTime = LocalTime.of(1,2,3,4);
        System.out.println(localTime);//輸出:01:02:03.000000004
        System.out.println("-------------------------------------------");
        localDateTime = LocalDateTime.of(localDate,localTime);
        System.out.println(localDateTime);//輸出:2023-08-02T01:02:03.000000004
        localDateTime = LocalDateTime.of(2024,1,1,1,1);
        System.out.println(localDateTime);//輸出:2024-01-01T01:01
        localDateTime = LocalDateTime.of(2024,1,1,1,1,1);
        System.out.println(localDateTime);//輸出:2024-01-01T01:01:01
        localDateTime = LocalDateTime.of(2024,1,1,1,1,1,1);
        System.out.println(localDateTime);//輸出:2024-01-01T01:01:01.000000001
        localDateTime = LocalDateTime.of(2024,Month.of(2),1,1,1,1,1);
        System.out.println(localDateTime);//輸出:2024-02-01T01:01:01.000000001
    }
} 

示例2:

 @Test
    public void test2(){
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);//輸出:2020-06-30
        localDate = localDate.plusYears(1);
        System.out.println(localDate);//輸出:2021-06-30
        localDate = localDate.plusMonths(2);
        System.out.println(localDate);//輸出:2021-08-30
        localDate = localDate.plusDays(3);
        System.out.println(localDate);//輸出:2021-09-02
        localDate = localDate.plusWeeks(4);
        System.out.println(localDate);//輸出:2021-09-30
        localDate = localDate.plus(Period.ofDays(10));//加10天
        System.out.println(localDate);//輸出:2021-10-10
        localDate = localDate.plus(Period.of(1,2,3));//加一年兩個月三天
        System.out.println(localDate);//輸出:2022-12-13
        localDate = localDate.plus(Period.ofYears(2));//加兩年
        System.out.println(localDate);//輸出:2024-12-13
        localDate = localDate.plus(1, ChronoUnit.DAYS);//加一天
        System.out.println(localDate);//輸出:2024-12-14
        localDate = localDate.plus(1, ChronoUnit.MONTHS);//加一個月
        System.out.println(localDate);//輸出:2025-01-14
        System.out.println("-------------------------------------------");
        localDate = localDate.minusYears(1);
        System.out.println(localDate);//輸出:2024-01-14
        localDate.minusMonths(1);
        localDate.minusDays(1);
        localDate.minusWeeks(1);
        localDate.minus(Period.ofYears(2));
        //..........其餘用法和plus同樣...........
        System.out.println("-------------------------------------------");

        LocalTime localTime = LocalTime.now();
        System.out.println(localTime);//輸出:21:35:54.776
        localTime = localTime.plusHours(1);
        System.out.println(localTime);//輸出:22:35:54.776
        //..........其餘用法和localDate的同樣...........
        //..........LocalDateTime的用法也同樣...........
    }

示例3:

    @Test
    public void test3(){
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);//輸出:2020-06-30
        System.out.println(localDate.getYear());//輸出:2020
        System.out.println(localDate.getDayOfMonth());//輸出:30
        //..........等.......

        //將天數、月份、等修改成指定的值
        localDate = localDate.withDayOfMonth(22);
        System.out.println(localDate);//輸出:2020-06-22
        localDate = localDate.withMonth(11);
        System.out.println(localDate);//輸出:2020-11-22
        localDate = localDate.with(LocalDate.now());
        System.out.println(localDate);//輸出:2020-06-30
        //..........等.......
        System.out.println("-------------------------------------------");

        Period period = localDate.until(LocalDate.of(2020, 1, 1));
        System.out.println(period.get(ChronoUnit.YEARS));//輸出:0  相差 0 年
        System.out.println(period.get(ChronoUnit.MONTHS));//輸出:-5  相差 1 - 6 = -5 月
        System.out.println(period.get(ChronoUnit.DAYS));//輸出:-29  相差 1 - 30 = -29 天
        System.out.println("-------------------------------------------");

        System.out.println(localDate.isAfter(LocalDate.of(2020, 1, 1))); //輸出:true
        System.out.println(localDate.isBefore(LocalDate.of(2020, 1, 1))); //輸出:false
        System.out.println(localDate.isLeapYear());//是否閏年,輸出:true
    }

 

Instant 時間戳

 時間戳,以 Unix 元年:1970年1月1日00:00:00 到某個時間之間的毫秒值 。spa

示例:

    @Test
    public void test4() {
        Instant ins1 = Instant.now();    // 默認獲取UTC時區(世界協調時間,基本上是美國鬼子使用,和中國時間相差大概8小時)
        System.out.println(ins1);//輸出結果:2020-06-30T14:28:05.217Z

        // 偏移量運算
        OffsetDateTime offsetDateTime = ins1.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);// 輸出結果:2020-06-30T22:28:05.217+08:00    當前系統時間,國際標準的顯示時間方式

        // 獲取時間戳
        System.out.println(ins1.toEpochMilli());//輸出結果:1593527285217

        // 以Unix元年爲起點,進行偏移量運算
        Instant ins2 = Instant.ofEpochSecond(60);
        System.out.println(ins2);// 運行結果:1970-01-01T00:01:00Z
    }

 

Duration 和 Period 類

Duration : 計算兩個 「時間」 之間的間隔。code

Period:計算兩個「日期」 之間的間隔。orm

示例:

    @Test
    public void test5() throws Exception {
        Instant ins1 = Instant.now();
        Thread.sleep(1000);
        Instant ins2 = Instant.now();

        Duration duration = Duration.between(ins1, ins2);
        System.out.println(duration.toMillis()); // 運行結果:1000

        LocalTime localTime_1 = LocalTime.of(20,1,2);
        LocalTime localTime_2 = LocalTime.of(20,2,2);

        System.out.println(Duration.between(localTime_1, localTime_2).toMillis());// 運行結果:60000

        System.out.println("-------------------------------------------");

        LocalDate localDate_1 = LocalDate.of(2020,1, 1);
        LocalDate localDate_2 = LocalDate.now();

        Period period = Period.between(localDate_1, localDate_2);
        System.out.println(period.getYears());      // 運行結果:0
        System.out.println(period.getMonths());     // 運行結果:5
        System.out.println(period.getDays());       // 運行結果:29
    }

日期的操縱

TemporalAdjuster : 時間校訂器。有時咱們可能須要獲取例如:將日期調整到「下個週日」等操做。
TemporalAdjusters : 該類經過靜態方法提供了大量的經常使用 TemporalAdjuster 的實現對象

示例:

    @Test
    public void test6(){

        //TemporalAdjuster : 時間校訂器。有時咱們可能須要獲取例如:將日期調整到「下個週日」等操做。
        //TemporalAdjusters : 該類經過靜態方法提供了大量的經常使用 TemporalAdjuster 的實現。
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);// 輸出:2020-07-01
        localDate = localDate.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println(localDate);// 輸出:2020-07-31
        localDate = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println(localDate);// 輸出:2020-08-02

        localDate = LocalDate.of(2020,7,3);//週五
        //自定義校訂器:獲取下一個工做日
        localDate = localDate.with(ld -> {
            LocalDate ld_ = (LocalDate) ld;
            DayOfWeek dayOfWeek =  ld_.getDayOfWeek();

            if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
                return ld_.plusDays(3);
            } else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
                return ld_.plusDays(2);
            } else {
                return ld_.plusDays(1);
            }
        });
        System.out.println(localDate);// 輸出:2020-07-06

    }

解析與格式化

java.time.format.DateTimeFormatter 類:該類提供了三種格式化方法:blog

  • 預約義的標準格式
  • 語言環境相關的格式
  • 自定義的格式

示例:

    @Test
    public void test7(){
        // DateTimeFormatter 格式化 時間/日期
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);// 輸出: 2020-07-01T21:56:11.978
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
        System.out.println(formatter.format(localDateTime));// 輸出: 2020-07-01
        formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH時mm分ss秒");
        System.out.println(formatter.format(localDateTime));// 輸出: 2020年07月01日 21時56分11秒
        System.out.println(formatter.parse("2020年07月01日 21時55分08秒"));// 輸出: {},ISO resolved to 2020-07-01T21:55:08

        System.out.println(localDateTime.parse("2020年07月01日 21時55分08秒",formatter));// 輸出: 2020-07-01T21:55:08

    }

時區的處理

Java8 中加入了對時區的支持,帶時區的時間爲分別爲:ZonedDate、 ZonedTime、 ZonedDateTime
其中每一個時區都對應着 ID,地區ID都爲 「{區域}/{城市}」的格式,例如 : Asia/Shanghai 等。get

  • ZoneId:該類中包含了全部的時區信息
  • getAvailableZoneIds() : 能夠獲取全部時區時區信息
  • of(id) : 用指定的時區信息獲取 ZoneId 對象

示例:

    @Test
    public void test8(){
        //時區:ZonedDate、 ZonedTime、 ZonedDateTime

        Set<String> zoneIds = ZoneId.getAvailableZoneIds();//獲取全部時區
        System.out.println(zoneIds);//輸出: [Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8, Africa/Nairobi, America/Marigot, Asia/Aqtau, .....等等.....
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);// 輸出: 2020-07-01T22:06:59.130
        localDateTime = LocalDateTime.now(ZoneId.of("America/Marigot"));
        System.out.println(localDateTime);// 輸出: 2020-07-01T10:06:59.131
        localDateTime = LocalDateTime.now(ZoneId.of("Etc/GMT+8"));
        System.out.println(localDateTime);// 輸出: 2020-07-01T06:06:59.131
        System.out.println("-------------------------------------------");
        localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);// 輸出: 2020-07-01T22:10:39.940
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Europe/Vatican"));//帶時區的日期時間
        System.out.println(zonedDateTime);// 輸出: 2020-07-01T22:10:39.940+02:00[Europe/Vatican]

    }

 

 

相關文章
相關標籤/搜索