Search code examples
javadatetime-formatstring-to-datetime

I want to parse string as date using DateTimeFormatter with in "MMdd" but it is even parsing string like "3212" which is wrong


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

Solution

  • 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.