jdk1.8中时间类
时间: 2023-12-17 18:28:56 浏览: 39
在JDK1.8中,时间类主要有两个:`LocalDate`和`LocalDateTime`。其中,`LocalDate`表示日期,`LocalDateTime`表示日期和时间。
以下是`LocalDate`和`LocalDateTime`的使用示例:
```java
// 获取当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("Current date: " + currentDate); // 输出:Current date: 2022-01-01
// 获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current date and time: " + currentDateTime); // 输出:Current date and time: 2022-01-01T00:00:00.000
// 根据指定日期创建LocalDate对象
LocalDate date = LocalDate.of(2021, 12, 31);
System.out.println("Date: " + date); // 输出:Date: 2021-12-31
// 根据指定日期和时间创建LocalDateTime对象
LocalDateTime dateTime = LocalDateTime.of(2021, 12, 31, 23, 59, 59);
System.out.println("Date and time: " + dateTime); // 输出:Date and time: 2021-12-31T23:59:59
// 获取指定日期的年、月、日
int year = date.getYear();
int month = date.getMonthValue();
int day = date.getDayOfMonth();
System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day); // 输出:Year: 2021, Month: 12, Day: 31
// 获取指定日期和时间的小时、分钟、秒
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
System.out.println("Hour: " + hour + ", Minute: " + minute + ", Second: " + second); // 输出:Hour: 23, Minute: 59, Second: 59
```