DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMdd");
dateTimeFormatter.parse("3212");
1 回答
为了获得您期望的错误消息,您需要解析为适当排序的日期时间对象。您的代码仅解析字符串,而不是试图解释它。所以没有发现没有第 32 个月。尝试例如:
dateTimeFormatter.parse("3212", MonthDay::from);
这产生:
线程“main”java.time.format.DateTimeParseException 中的异常:无法解析文本“3212”:无法从 TemporalAccessor 获取 MonthDay:{MonthOfYear=32, DayOfMonth=12},java.time.format.Parsed 类型的 ISO
为什么会这样?Java 认为您的格式化程序独立于特定的日历系统或年表。您可以检查dateTimeFormatter.getChronology()
返回null
。正如 Arnaud Denoyelle 在评论DateTimeFormatter.parse
中指出的那样,您调用的单参数方法返回 a TemporalAccessor
。的文档TemporalAccessor
说:
此接口的实现可能在 ISO 以外的日历系统中。
一些日历系统有 13 个月(在某些年份)。与其对月份数(13?14?15?)设置任意限制,不如将其留给您通常用于保存数据的具体日期和时间类。我使用的MonthDay
类代表“ISO-8601 日历系统中的月日”,其中一年总是有 12 个月,所以现在我们得到了预期的异常。