java.time.LocalDateTime的用法
时间: 2023-10-14 11:28:45 浏览: 50
Java的java.time.LocalDateTime类可以表示日期和时间,包括年、月、日、小时、分钟、秒和纳秒。
以下是java.time.LocalDateTime类的使用示例:
1. 创建一个LocalDateTime实例:
```
LocalDateTime now = LocalDateTime.now();
```
2. 通过指定的年、月、日、小时、分钟和秒创建一个LocalDateTime实例:
```
LocalDateTime dateTime = LocalDateTime.of(2021, 9, 22, 12, 30, 0);
```
3. 获取LocalDateTime实例的年、月、日、小时、分钟和秒:
```
int year = dateTime.getYear();
int month = dateTime.getMonthValue();
int day = dateTime.getDayOfMonth();
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
```
4. 对LocalDateTime实例进行加减操作:
```
LocalDateTime tomorrow = now.plusDays(1);
LocalDateTime yesterday = now.minusDays(1);
```
5. 比较两个LocalDateTime实例的大小:
```
boolean isAfter = now.isAfter(dateTime);
boolean isBefore = now.isBefore(dateTime);
```
6. 格式化LocalDateTime实例:
```
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
```
以上是java.time.LocalDateTime类的一些基本用法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)