java.time.temporal.ChronoUnit 枚舉在 Java8 中添加,以取代舊的API用來代表日,月等整數值
讓我們來看看他們的操作。
使用所選擇的任何編輯器創建下面的java程序在 C:/> JAVA
Java8Tester.java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Java8Tester {
public static void main(String args[]){
Java8Tester java8tester = new Java8Tester();
java8tester.testChromoUnits();
}
public void testChromoUnits(){
//Get the current date
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 week to the current date
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("Next week: " + nextWeek);
//add 1 month to the current date
LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + nextMonth);
//add 1 year to the current date
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("Next year: " + nextYear);
//add 10 years to the current date
LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES);
System.out.println("Date after ten year: " + nextDecade);
}
}
驗證結果
使用javac編譯器編譯如下類
C:\JAVA>javac Java8Tester.java
現在運行Java8Tester看到的結果
C:\JAVA>java Java8Tester
看到結果
Current date: 2014-12-10
Next week: 2014-12-17
Next month: 2015-01-10
Next year: 2015-12-10
Date after ten year: 2024-12-10