Java 把LocalDateTime类型的时间格式化yyyy-mm-dd,并以LocalDateTime类型打印
时间: 2023-08-12 15:59:14 浏览: 54
在Java中,`LocalDateTime`类型是不可变的,它表示日期和时间,而不是特定的格式。但是,你可以使用`DateTimeFormatter`将`LocalDateTime`对象格式化为指定的字符串,并将其以`LocalDateTime`类型打印出来。
以下是示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDateTime = now.format(formatter);
LocalDateTime parsedDateTime = LocalDateTime.parse(formattedDateTime, formatter);
System.out.println("Formatted DateTime (String): " + formattedDateTime);
System.out.println("Parsed DateTime (LocalDateTime): " + parsedDateTime);
}
}
```
该代码首先创建了一个`LocalDateTime`对象表示当前的日期和时间。然后,使用`DateTimeFormatter`将其格式化为"yyyy-MM-dd"的字符串形式,并将结果存储在`formattedDateTime`变量中。
接下来,使用相同的`formatter`将`formattedDateTime`字符串解析为`LocalDateTime`对象,并将结果存储在`parsedDateTime`变量中。
最后,通过打印两个变量,你可以看到格式化后的字符串和解析后的`LocalDateTime`对象。
请注意,格式化后的字符串是以字符串形式展示的,而解析后的对象是以`LocalDateTime`类型展示的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)