Java8时间调节器 - 极悦

JDK新特性

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

 

技术文档推荐

更多>>

视频教程推荐

更多>>