Java8 時間調節器


TemporalAdjuster 是做日期數學計算。例如,要獲得「本月第二個星期六」或「下週二」。

讓我們來看看他們的操作。

選擇使用任何編輯器創建以下java程序在 C:/> JAVA

Java8Tester.java
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;

public class Java8Tester {
   public static void main(String args[]){
      Java8Tester java8tester = new Java8Tester();
      java8tester.testAdjusters(); 	  
   }

   public void testAdjusters(){
      //Get the current date
      LocalDate date1 = LocalDate.now();
      System.out.println("Current date: " + date1);	  

      //get the next tuesday
      LocalDate nextTuesday = date1.with(TemporalAdjusters.next(DayOfWeek.TUESDAY));
      System.out.println("Next Tuesday on : " + nextTuesday);

      //get the second saturday of next month
      LocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1);

      LocalDate secondSaturday = firstInYear.with(
         TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)).with(
         TemporalAdjusters.next(DayOfWeek.SATURDAY));
      System.out.println("Second saturday on : " + secondSaturday);	   
   }	
}

驗證結果

使用javac編譯器編譯如下類

C:\JAVA>javac Java8Tester.java

現在運行Java8Tester看到的結果

C:\JAVA>java Java8Tester

看到結果。

Current date: 2014-12-10                                                 
Next Tuesday on : 2014-12-16                                             
Second saturday on : 2014-12-13