Java8 本地DateTime API
LocalDate/本地時間和LocalDateTime類簡化時區不需要開發。
讓我們來看看他們操作。
選擇使用任何編輯器創建以下java程序在 C:/> JAVA
Java8Tester.javaimport java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; import java.time.Month; public class Java8Tester { public static void main(String args[]){ Java8Tester java8tester = new Java8Tester(); java8tester.testLocalDateTime(); } public void testLocalDateTime(){ // Get the current date and time LocalDateTime currentTime = LocalDateTime.now(); System.out.println("Current DateTime: " + currentTime); LocalDate date1 = currentTime.toLocalDate(); System.out.println("date1: " + date1); Month month = currentTime.getMonth(); int day = currentTime.getDayOfMonth(); int seconds = currentTime.getSecond(); System.out.println("Month: " + month +"day: " + day +"seconds: " + seconds ); LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012); System.out.println("date2: " + date2); //12 december 2014 LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12); System.out.println("date3: " + date3); //22 hour 15 minutes LocalTime date4 = LocalTime.of(22, 15); System.out.println("date4: " + date4); //parse a string LocalTime date5 = LocalTime.parse("20:15:30"); System.out.println("date5: " + date5); } }
驗證結果
使用javac編譯器編譯如下類
C:\JAVA>javac Java8Tester.java
現在運行Java8Tester看到的結果
C:\JAVA>java Java8Tester
看到結果
Current DateTime: 2014-12-09T11:00:45.457 date1: 2014-12-09 Month: DECEMBERday: 9seconds: 45 date2: 2012-12-10T11:00:45.457 date3: 2014-12-12 date4: 22:15 date5: 20:15:30