我们先来看以下代码:
public class test {
private final static DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final static DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM dd, yyyy HH:mm:ss a");
public static void main(String[] args) {
String str1 = "2020-11-11 11:11";
String str2 = "May 05, 2020 10:24:51 AM";
LocalDateTime time1 = LocalDateTime.parse(str1, dtf1);
System.out.println(time1);
LocalDateTime time2 = LocalDateTime.parse(str2, dtf2);
System.out.println(time2);
}
}
执行结果:我们发现,几乎是相同的代码,为什么str1就能顺利转变成LocalDateTime,而str2就会报错,而且是在第0位就报错呢?
经过查阅资料,我从这篇博客(虽然说的不是一件事)中获得了提示,即有可能是Locale的问题。于是我对第三行代码进行了修正:
public class test {
private final static DateTimeFo