DateTimeFormatter 编码
时间: 2024-01-06 18:24:35 浏览: 34
DateTimeFormatter 是 Java 8 中的一个类,用于格式化和解析日期时间对象。它可以根据指定的模式将日期时间对象转换为字符串,也可以将字符串解析为日期时间对象。
以下是一个使用 DateTimeFormatter 的示例:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
// 创建一个 DateTimeFormatter 对象,指定日期时间的格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 将日期时间对象格式化为字符串
LocalDateTime dateTime = LocalDateTime.now();
String formattedDateTime = dateTime.format(formatter);
System.out.println("Formatted DateTime: " + formattedDateTime);
// 将字符串解析为日期时间对象
String strDateTime = "2022-01-01 12:00:00";
LocalDateTime parsedDateTime = LocalDateTime.parse(strDateTime, formatter);
System.out.println("Parsed DateTime: " + parsedDateTime);
}
}
```
输出结果:
```
Formatted DateTime: 2022-01-01 12:00:00
Parsed DateTime: 2022-01-01T12:00
```
在上面的示例中,我们首先创建了一个 DateTimeFormatter 对象,指定了日期时间的格式为"yyyy-MM-dd HH:mm:ss"。然后,我们使用该格式化器将当前的日期时间对象格式化为字符串,并将其打印出来。接下来,我们将一个字符串解析为日期时间对象,并将其打印出来。