天天看點

Java8計算日期時間差1 Period類Duration類3 ChronoUnit類

1 Period類

方法getYears(),getMonths()和getDays()。

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;

public class Test {

    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today : " + today);
        LocalDate birthDate = LocalDate.of(1993, Month.OCTOBER, 19);
        System.out.println("BirthDate : " + birthDate);

        Period p = Period.between(birthDate, today);
        System.out.printf("年齡 : %d 年 %d 月 %d 日", p.getYears(), p.getMonths(), p.getDays());
    }
}      
Today : 2017-06-16
BirthDate : 1993-10-19
年齡 : 23 年 7 月 28 日      

Duration類

基于時間的值(如秒,納秒)測量時間量的方法。

import java.time.Duration;
import java.time.Instant;

public class Test {

    public static void main(String[] args) {
        Instant inst1 = Instant.now();
        System.out.println("Inst1 : " + inst1);
        Instant inst2 = inst1.plus(Duration.ofSeconds(10));
        System.out.println("Inst2 : " + inst2);

        System.out.println("Difference in milliseconds : " + Duration.between(inst1, inst2).toMillis());

        System.out.println("Difference in seconds : " + Duration.between(inst1, inst2).getSeconds());

    }
}      
Inst1 : 2017-06-16T07:46:45.085Z
Inst2 : 2017-06-16T07:46:55.085Z
Difference in milliseconds : 10000
Difference in seconds : 10      

3 ChronoUnit類

ChronoUnit類可用于在單個時間機關内測量一段時間,例如天數或秒。

以下是使用between()方法來查找兩個日期之間的差別的示例。

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class Test {

    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(1993, Month.OCTOBER, 19);
        System.out.println("開始時間  : " + startDate);

        LocalDate endDate = LocalDate.of(2017, Month.JUNE, 16);
        System.out.println("結束時間 : " + endDate);

        long daysDiff = ChronoUnit.DAYS.between(startDate, endDate);
        System.out.println("兩天之間的差在天數   : " + daysDiff);

    }
}      
開始時間  : 1993-10-19
結束時間 : 2017-06-16
兩天之間的差在天數   : 8641