Java Spring Boot使用DateTimeFormatter报错Unsupported field: DayOfMonth怎么解决
报错根因
你调用format方法的对象是YearMonth类型,该类型仅保存年、月两个时间字段,而你使用的DateTimeFormatter.ISO_LOCAL_DATE_TIME(包括你注释里写的yyyy-MM-dd格式)要求必须存在DayOfMonth(日)字段,YearMonth无法提供对应字段值,因此抛出UnsupportedTemporalTypeException。
另外你之前用的ISO_LOCAL_DATE_TIME生成的是带时分秒的字符串(比如2021-06-01T00:00:00),和你现有Map中2021-06-01格式的key完全不匹配,就算格式不报错也无法正确匹配已有的数据。
修复方案
你现有Map的key都是每月1号的日期格式,只需要给YearMonth补全1号的日字段,再用匹配的格式器格式化即可,修复后代码如下:
Map<String, Long> expectedValues = new HashMap<>(); expectedValues.put("2021-06-01", 10L); expectedValues.put("2021-07-01", 20L); expectedValues.put("2021-08-01", 30L); YearMonth thisMonth = YearMonth.now(); // 格式器和现有key的格式保持一致,放到循环外避免重复创建 DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); for (int i = 0; i < 12; i++) { YearMonth prevMonth = thisMonth.minusMonths(i); // 补全当月1号,转为LocalDate后再格式化 String prevYearMonthStr = prevMonth.atDay(1).format(monthYearFormatter); expectedValues.putIfAbsent(prevYearMonthStr, 0L); }
额外优化:可以直接用Map的putIfAbsent方法替代判空后再赋值的逻辑,代码更简洁。
内容的提问来源于stack exchange,提问作者sandeep。
相关产品推荐
相关产品推荐

