DateTimeFormatter.ofPattern 怎么返回时分秒
时间: 2023-08-05 18:59:08 浏览: 52
你可以使用`DateTimeFormatter.ofPattern`方法来创建一个指定格式的日期时间格式化器,并通过该格式化器将时分秒添加到日期时间中。以下是一个示例:
```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("HH:mm:ss");
// 格式化日期时间,返回时分秒的字符串
String formattedTime = now.format(formatter);
System.out.println(formattedTime);
}
}
```
在上述示例中,我们创建了一个`LocalDateTime`对象来表示当前的日期时间。然后,我们使用`DateTimeFormatter.ofPattern`方法创建了一个格式化器,其中的模式字符串`"HH:mm:ss"`表示小时、分钟和秒。最后,我们调用`format`方法,将当前日期时间格式化为时分秒的字符串,并将其打印输出。
请注意,这里使用的是`HH:mm:ss`来表示24小时制的时分秒。如果要使用12小时制,请使用`hh:mm:ss a`作为模式字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![avi](https://img-home.csdnimg.cn/images/20210720083319.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)