LocalDate、LocalTime。LocalDateTime基本用法代码
时间: 2024-02-02 19:10:15 浏览: 80
以下是关于LocalDate、LocalTime和LocalDateTime的基本用法代码示例:
1. LocalDate的基本用法:
```java
// 获取当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("当前日期: " + currentDate);
// 创建指定日期
LocalDate specificDate = LocalDate.of(2022, 12, 31);
System.out.println("指定日期: " + specificDate);
// 获取年、月、日
int year = specificDate.getYear();
int month = specificDate.getMonthValue();
int day = specificDate.getDayOfMonth();
System.out.println("年: " + year + ", 月: " + month + ", 日: " + day);
// 日期比较
LocalDate date1 = LocalDate.of(2022, 1, 1);
LocalDate date2 = LocalDate.of(2022, 1, 2);
boolean isBefore = date1.isBefore(date2);
boolean isAfter = date1.isAfter(date2);
boolean isEqual = date1.isEqual(date2);
System.out.println("date1是否在date2之前: " + isBefore);
System.out.println("date1是否在date2之后: " + isAfter);
System.out.println("date1是否等于date2: " + isEqual);
```
2. LocalTime的基本用法:
```java
// 获取当前时间
LocalTime currentTime = LocalTime.now();
System.out.println("当前时间: " + currentTime);
// 创建指定时间
LocalTime specificTime = LocalTime.of(12, 30, 45);
System.out.println("指定时间: " + specificTime);
// 获取时、分、秒
int hour = specificTime.getHour();
int minute = specificTime.getMinute();
int second = specificTime.getSecond();
System.out.println("时: " + hour + ", 分: " + minute + ", 秒: " + second);
// 时间比较
LocalTime time1 = LocalTime.of(10, 30);
LocalTime time2 = LocalTime.of(12, 30);
boolean isBefore = time1.isBefore(time2);
boolean isAfter = time1.isAfter(time2);
boolean isEqual = time1.equals(time2);
System.out.println("time1是否在time2之前: " + isBefore);
System.out.println("time1是否在time2之后: " + isAfter);
System.out.println("time1是否等于time2: " + isEqual);
```
3. LocalDateTime的基本用法:
```java
// 获取当前日期时间
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("当前日期时间: " + currentDateTime);
// 创建指定日期时间
LocalDateTime specificDateTime = LocalDateTime.of(2022, 12, 31, 12, 30, 45);
System.out.println("指定日期时间: " + specificDateTime);
// 获取年、月、日、时、分、秒
int year = specificDateTime.getYear();
int month = specificDateTime.getMonthValue();
int day = specificDateTime.getDayOfMonth();
int hour = specificDateTime.getHour();
int minute = specificDateTime.getMinute();
int second = specificDateTime.getSecond();
System.out.println("年: " + year + ", 月: " + month + ", 日: " + day);
System.out.println("时: " + hour + ", 分: " + minute + ", 秒: " + second);
// 日期时间比较
LocalDateTime dateTime1 = LocalDateTime.of(2022, 1, 1, 10, 30);
LocalDateTime dateTime2 = LocalDateTime.of(2022, 1, 2, 12, 30);
boolean isBefore = dateTime1.isBefore(dateTime2);
boolean isAfter = dateTime1.isAfter(dateTime2);
boolean isEqual = dateTime1.equals(dateTime2);
System.out.println("dateTime1是否在dateTime2之前: " + isBefore);
System.out.println("dateTime1是否在dateTime2之后: " + isAfter);
System.out.println("dateTime1是否等于dateTime2: " + isEqual);
}
```
阅读全文