Skip to content

DateTimeFormatter

DateTimeFormatter 是 Java 8 java.time 包里的一个日期时间格式化/解析工具类,用于替代旧的 SimpleDateFormat线程安全、功能更强。

ofPattern

创建格式化器

java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

format

格式化(对象 → 字符串)

java
@Test
public void shouldFormatLocalDateTimeWithCommonPattern() {
    LocalDateTime localDateTime = LocalDateTime.of(2026, 3, 24, 10, 30, 15);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    String formattedDateTime = localDateTime.format(formatter);

    System.out.println("格式化前时间: " + localDateTime);//2026-03-24T10:30:15
    System.out.println("常用格式化结果: " + formattedDateTime);//2026-03-24 10:30:15
}

parse

解析(字符串 → 对象)

java
@Test
public void shouldFormatLocalDateTimeWithChinesePattern() {
    LocalDateTime localDateTime = LocalDateTime.of(2026, 3, 24, 10, 30, 15);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");

    String formattedDateTime = localDateTime.format(formatter);

    System.out.println("格式化前时间: " + localDateTime);//格式化前时间: 2026-03-24T10:30:15
    System.out.println("中文格式化结果: " + formattedDateTime);//中文格式化结果: 2026年03月24日 10时30分15秒
}