如何在Java8中獲取今天的日期?


在Java8之前,我們通常依賴於各種類來獲取當前日期和時間,如SimpleDateFormat、Calendar等。

示例

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LocalDateJava8 {
   public static void main(String args[]) {
      Date date = new Date();
      String timeFormatString = "hh:mm:ss a";
      DateFormat timeFormat = new SimpleDateFormat(timeFormatString);
      String currentTime = timeFormat.format(date);
      System.out.println("Current time: "+currentTime);
      String dateFormatString = "EEE, MMM d, ''yy";
      DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
      String currentDate = dateFormat.format(date);
      System.out.println("Current date: "+currentDate);
   }
}

輸出

Current time: 05:48:34 PM
Current date: Wed, Jul 24, '19

Java8中的日期和時間

從Java8開始引入了java.time包。該包提供了LocalDate、LocalTime、LocalDateTime、MonthDay等類。使用此包中的類,您可以更簡單地獲取時間和日期。

Java.time.LocalDate − 此類表示ISO-8601日曆系統中不含時區的日期物件。此類的now()方法從系統時鐘獲取當前日期。

Java.time.LocalTime − 此類表示ISO-8601日曆系統中不含時區的時刻物件。此類的now()方法從系統時鐘獲取當前時間。

Java.time.LocalDateTime − 此類表示ISO-8601日曆系統中不含時區的日期時間物件。此類的now()方法從系統時鐘獲取當前日期時間。

示例

以下示例使用Java8的java.time包檢索當前日期、時間和日期時間的值。

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class LocalDateJava8 {
   public static void main(String args[]) {
      //Getting the current date value
      LocalDate date = LocalDate.now();
      System.out.println("Current date: "+date);
      //Getting the current time value
      LocalTime time = LocalTime.now();
      System.out.println("Current time: "+time);
      //Getting the current date-time value
      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println("Current date-time: "+dateTime);
   }
}

輸出

Current date: 2019-07-24
Current time: 18:08:05.923
Current date-time: 2019-07-24T18:08:05.923

更新日期: 07-08-2019

3K+ 瀏覽量

開始你的職業

完成課程獲取認證

開始
廣告
© . All rights reserved.