DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMdd");
dateTimeFormatter.parse("3212");

- 17,626
- 12
- 64
- 115

- 33
- 2
-
1@OleV.V. I believe you should be able to reopen the question... – user85421 Aug 13 '18 at 20:15
-
Danke schön, @Carlos, for the suggestion. I was aware that I could but wanted to give you a chance to argue against me before doing so, also because this question already had an accepted answer, so I didn’t consider it urgent. Thx for reopening the question. (Kommentar in Baden verfasst) – Ole V.V. Aug 14 '18 at 08:19
-
@OleV.V. Kein Problem (aus Weilimdorf) that sure was a *nicer way* to do it. – user85421 Aug 14 '18 at 08:50
1 Answers
In order to get the error message you expect, you need to parse into a datetime object of an appropriate sort. Your code is parsing the string only, not trying to interpret it. So it is not discovered that there is no 32nd month. Try for example:
dateTimeFormatter.parse("3212", MonthDay::from);
This yields:
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
Why is this so? Java perceives your formatter as independent of a particular calendar system or chronology. You may check that dateTimeFormatter.getChronology()
returns null
. As Arnaud Denoyelle notes in a comment, the one-arg DateTimeFormatter.parse
method that you called returns a TemporalAccessor
. The documentation of TemporalAccessor
says:
implementations of this interface may be in calendar systems other than ISO.
Some calendar systems have 13 months (in some years). Rather than setting an arbitrary limit on month number (13? 14? 15?) it has been decided to leave this to the concrete date and time classes that you normally use for holding your data. The MonthDay
class that I use represents a “month-day in the ISO-8601 calendar system”, in which a year always has 12 months, so now we get the expected exception.

- 81,772
- 15
- 137
- 161
-
2Seems legit according to the javadoc about [TemporalAccessor](https://docs.oracle.com/javase/10/docs/api/java/time/temporal/TemporalAccessor.html) (which is the result type of `dateTimeFormatter.parse(...)`): "There are many reasons for this, part of which is that implementations of this interface may be in calendar systems other than ISO.". I don't have enough knowledge about that to upvote though. – Arnaud Denoyelle Aug 13 '18 at 12:42