java – 如何处理JSR 310中的大写或小写?
发布时间:2020-12-14 05:40:16 所属栏目:Java 来源:网络整理
导读:这个问题在这里已经有一个答案: How to parse case-insensitive strings with jsr310 DateTimeFormatter?2 如果一个月是UPPER或小写字母,即不是Title,DateTimeFormatter不能解析日期.有没有一个简单的方法来转换一个日期到标题的情况,或一种使格式化员更宽
这个问题在这里已经有一个答案:>
How to parse case-insensitive strings with jsr310 DateTimeFormatter?2
如果一个月是UPPER或小写字母,即不是Title,DateTimeFormatter不能解析日期.有没有一个简单的方法来转换一个日期到标题的情况,或一种使格式化员更宽松的方式? for (String date : "15-JAN-12,15-Jan-12,15-jan-12,15-01-12".split(",")) { try { System.out.println(date + " => " + LocalDate.parse(date,DateTimeFormatter.ofPattern("yy-MMM-dd"))); } catch (Exception e) { System.out.println(date + " => " + e); } } 版画 15-JAN-12 => java.time.format.DateTimeParseException: Text '15-JAN-12' could not be parsed at index 3 15-Jan-12 => 2015-01-12 15-01-12 => java.time.format.DateTimeParseException: Text '15-01-12' could not be parsed at index 3 15-jan-12 => java.time.format.DateTimeParseException: Text '15-jan-12' could not be parsed at index 3 解决方法
默认情况下,DateTimeFormatter是严格的区分大小写.使用DateTimeFormatterBuilder并指定parseCaseInsensitive()来解析不区分大小写.
DateTimeFormatter formatter = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("yy-MMM-dd") .toFormatter(Locale.US); 为了能够解析数字月份(即“15-01-12”),您还需要指定parseLenient(). DateTimeFormatter formatter = new DateTimeFormatterBuilder() .parseCaseInsensitive() .parseLenient() .appendPattern("yy-MMM-dd") .toFormatter(Locale.US); 您也可以更详细地指定不区分大小写/省略的月份部分: DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("yy-") .parseCaseInsensitive() .parseLenient() .appendPattern("MMM") .parseStrict() .parseCaseSensitive() .appendPattern("-dd") .toFormatter(Locale.US); 在理论上,这可能更快,但我不知道是否. PS:如果在年份之前指定parseLenient(),它也将正确解析4位数年份(即“2015-JAN-12”). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |