DateTimeFormatter.ofPattern()
时间: 2024-06-13 08:07:11 浏览: 12
`DateTimeFormatter.ofPattern()`是Java 8中的一个方法,用于创建自定义的日期时间格式模式。它接受一个字符串参数,该字符串定义了日期时间的格式。下面是一个示例:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// 创建自定义的日期时间格式模式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化日期时间
String formattedDateTime = now.format(formatter);
System.out.println("Formatted DateTime: " + formattedDateTime);
// 解析字符串为日期时间
LocalDateTime parsedDateTime = LocalDateTime.parse(formattedDateTime, formatter);
System.out.println("Parsed DateTime: " + parsedDateTime);
}
}
```
输出:
```
Formatted DateTime: 2021-01-01 12:34:56
Parsed DateTime: 2021-01-01T12:34:56
```
在上面的示例中,我们使用`DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")`创建了一个自定义的日期时间格式模式。然后,我们使用`now.format(formatter)`将当前日期时间格式化为字符串,并使用`LocalDateTime.parse(formattedDateTime, formatter)`将字符串解析为日期时间对象。