DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMdd");
dateTimeFormatter.parse("3212");
最佳答案
为了获得您期望的错误消息,您需要解析为适当排序的日期时间对象。您的代码仅解析字符串,而不尝试解释它。所以没有发现没有第32个月。尝试例如:
dateTimeFormatter.parse("3212", MonthDay::from);
这会产生:
Exception in thread "main" java.time.format.DateTimeParseException: Text '3212' could not be parsed: Unable to obtain MonthDay from TemporalAccessor: {MonthOfYear=32, DayOfMonth=12},ISO of type java.time.format.Parsed
为什么会这样?Java 将格式化程序视为独立于特定的日历系统或年表。您可以检查 dateTimeFormatter.getChronology()
是否返回 null
。正如 Arnaud Denoyelle 在 a comment 中指出的那样,您调用的单参数 DateTimeFormatter.parse
方法返回一个 TemporalAccessor
。 TemporalAccessor
的文档说:
implementations of this interface may be in calendar systems other than ISO.
某些日历系统有 13 个月(某些年份)。我们决定将其留给您通常用于保存数据的具体日期和时间类,而不是对月份数设置任意限制(13?14?15?)。我使用的 MonthDay
类表示“ISO-8601 日历系统中的月日”,其中一年总是有 12 个月,所以现在我们得到了预期的异常。
关于java - 我想使用 DateTimeFormatter 将字符串解析为日期 "MMdd"但它甚至解析像 "3212"这样的字符串,这是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51822257/