针对 某个值位数不一定的时候,用SimpleDateFormat 解析不报错,用DateTimeFormatter 解析报错的处理
说明:针对某个值的位数不固定的情况,可用用 ParsePosition 规定,从某个索引开始,按索引值与对应的时间值区匹配,而不是字段的长度与匹配格式不匹配就抛出异常 public void testDate3() throws ParseException {
DateTimeFormatter settleTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.S]");
String date = "2021-02-26 10:50:07";
String date1 = "2021-02-26 10:50:07.1";
String date2 = "2021-02-26 10:50:07.17";
String date3 = "2021-02-26 10:50:07.172";
// 针对某个值的位数不固定的情况,可用用 ParsePosition 规定,从某个索引开始,按索引值与对应的时间值区匹配
TemporalAccessor parse = settleTimeFormatter.parse(date,new ParsePosition(0));
TemporalAccessor parse1 = settleTimeFormatter.parse(date1,new ParsePosition(0));
TemporalAccessor parse2 = settleTimeFormatter.parse(date2,new ParsePosition(0));
TemporalAccessor parse3 = settleTimeFormatter.parse(date3,new ParsePosition(0));
System.out.println(parse);
System.out.println(parse1);
System.out.println(parse2);
System.out.println(parse3);
}