Java8日期和時間段的計算

在這裏插入圖片描述

前言

在Java8之前,計算日期相差多少天一般的做法都是藉助SimpleDateFormat對兩個日期格式化之後在進行比較。在編寫代碼的過程中,計算一個方法具體耗時多少分鐘,執行了多少秒等需求,一般也是藉助System.currentTimeMillis()。


long start = System.currentTimeMillis();

//業務邏輯
//...

long end = System.currentTimeMillis();
System.out.println("此處消耗了:"+(end-start));

下面看看在Java8中如何計算日期差以及時間差。

Java8中計算日期差

比如日期A是1992-08-01 到 今天(2020-02-25)一共相差多少天:

代碼1 如下:

public class Demo {

    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(1992, Month.AUGUST, 1);
        System.out.println("日期A : " + startDate);

        LocalDate endDate = LocalDate.of(2020, Month.FEBRUARY, 25);
        System.out.println("日期B : " + endDate);

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

輸出的結果:


日期A : 1992-08-01
日期B : 2020-02-25
兩個日期之間的差在天數   : 10069

代碼2 如下:

public class Demo {

    public static void main(String[] args) {
        Period period = Period.between(LocalDate.of(1992, 8, 1), LocalDate.of(2020, 2, 25));
        System.out.println("兩個日期之間的差   : " + period.getYears()+"年,"+period.getMonths()+"月,"+period.getDays()+"天");
    }
}

輸出的結果:

兩個日期之間的差   : 27年,6月,24天

ChronoUnit 類可用於在單個時間單位內測量一段時間,例如天數或秒。

Period類 主要用方法getYears(),getMonths()和getDays()來計算。

Java8中計算時間差

列如文中說的計算某個方法運行耗時了多長,具體代碼如下:

public class Demo {

    public static void main(String[] args) {

        Instant start = Instant.now();

        // 假設是業務邏輯部分代碼
        for (int i = 0; i <100000 ; i++) {
            System.out.println("---"+i);
        }

        Instant end = Instant.now();
        System.out.println("此處消耗了(s): " + Duration.between(start, end).getSeconds());
    }
}

輸出的結果:

--- ...
---99994
---99995
---99996
---99997
---99998
---99999
此處消耗了(s): 1

Duration 類提供了使用基於時間的值(如秒,納秒)測量時間量的方法。

關於三個類更多的說明,可自行參考官方API。

https://docs.oracle.com/javase/8/docs/api/index.html (官方API)

http://www.matools.com/api/java8 (中文版API)

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