Java 日期与时间
Java 日期
Java 没有内置的 Date 类,但我们可以导入 java.time 包来使用日期和时间 API。这个包还包括许多日期和时间类。例如:
| 类 | 描述 |
|---|---|
| LocalDate | 表示一个日期 (年, 月, 日 (yyyy-MM-dd)) |
| LocalTime | Represents a time (时, 分, 秒 和 纳秒 (HH-mm-ss-ns)) |
| LocalDateTime | 表示日期时间 (yyyy-MM-dd-HH-mm-ss-ns) |
| DateTimeFormatter | 用于显示和转换日期时间对象的格式化程序 |
如果您不明白什么是包, 可以访问本站的 Java 包教程。
显示当前日期
要显示当前日期,请导入 java.time.LocalDate 类,并使用其 now() 方法:
实例
import java.time.LocalDate; // import the LocalDate classpublic class Main {public static void main(String[] args) {LocalDate myObj = LocalDate.now(); // Create a date objectSystem.out.println(myObj); // Display the current date}}
输出结果为:
2022-03-04
显示当前时间
要显示当前时间(小时、分钟、秒和纳秒),请导入 java.time.LocalTime 类并使用其 now() 方法:
实例
import java.time.LocalTime; // import the LocalTime classpublic class Main {public static void main(String[] args) {LocalTime myObj = LocalTime.now();System.out.println(myObj);}}
结果输出为:
07:48:15.729750
显示当前日期和时间
要显示当前日期和时间,请导入 java.time.LocalDateTime 类,并使用其 now() 方法:
实例
import java.time.LocalDateTime; // import the LocalDateTime classpublic class Main {public static void main(String[] args) {LocalDateTime myObj = LocalDateTime.now();System.out.println(myObj);}}
结果输出为:
2022-03-04T07:48:15.729015
格式化日期和时间
上例中的 "T" 用于区分日期和时间。可以在同一个包中使用 DateTimeFormatter 类和 ofPattern() 方法来格式化或解析日期时间对象。以下示例将从日期时间中删除 "T" 和纳秒:
实例
import java.time.LocalDateTime; // Import the LocalDateTime classimport java.time.format.DateTimeFormatter; // Import the DateTimeFormatter classpublic class Main {public static void main(String[] args) {LocalDateTime myDateObj = LocalDateTime.now();System.out.println("Before formatting: " + myDateObj);DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");String formattedDate = myDateObj.format(myFormatObj);System.out.println("After formatting: " + formattedDate);}}
结果输出为:
Before Formatting: 2022-03-04T07:48:15.729045
After Formatting: 04-03-2022 07:48:15
After Formatting: 04-03-2022 07:48:15
如果希望以不同的格式显示日期和时间,ofPattern() 方法可以接受各种值.例如:
| 值 | 实例 | 试一试 |
|---|---|---|
| yyyy-MM-dd | "2022-03-01" | 试一试 » |
| dd/MM/yyyy | "01/03/2022" | 试一试 » |
| dd-MMM-yyyy | "01-03-2022" | 试一试 » |
| E, MMM dd yyyy | "Thu, 03 01 2022" | 试一试 » |