天天看點

LocalDateTime的格式化問題

背景

  • 把"20200319143000000"的日期格式轉化為"2020-03-19 14:30:00:000"
  • 之前一直用SimpleDateFormat,這次想要LocalDateTime格式化
// 使用SimpleDateFormat格式化
String before = "20200319143000000";
try {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String after = sdf2.format(sdf1.parse(before));
        System.out.println(after);
} catch (ParseException e) {
        e.printStackTrace();
}

// 使用LocalDateFormat,報錯
String before = "20200319143000000";
String after = LocalDateTime.parse(before, DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
           

報錯

Exception in thread "main" java.time.format.DateTimeParseException: Text '20200319143000000' could not be parsed at index 0
           

解決

  • LocalDateTime格式化需要在日期和時間之間有空格分隔
String before = "20200319143000000";
String after = LocalDateTime.parse(new StringBuilder(before).insert(8, " "), DateTimeFormatter.ofPattern("yyyyMMdd HHmmssSSS")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
           

繼續閱讀