2

I expected an exception from:

LocalDate.parse("9/31/2018",DateTimeFormatter.ofPattern("M/d/yyyy"));

but instead I got Sep 30, 2018!? Don't get me wrong, it's nice that it's being smart, but I have come to expect a heightened level of precision from Java's Date classes...

Can anyone shed some light on how/why? This is going to mess with my tests.

end-user
  • 2,845
  • 6
  • 30
  • 56
  • Fascinating. I would've expected that it would be corrected to 'October 1, 2018' since you're one day too far in the future, not past. For what it's worth, it's just calling the formatter's parse method like `parse( date, LocalDate::from )`. – Roddy of the Frozen Peas May 07 '19 at 19:59
  • Yeah, that's what I had with Date and SimpleDateFormatter. But, I'd really rather just a flat exception because I wouldn't expect 9/32/2018 to become Oct 2, etc. – end-user May 07 '19 at 20:04

1 Answers1

8

This is due to the ResolverStyle used by the formatter to parse the value. By default (at least on my machine) it's "smart":

For example, resolving year-month and day-of-month in the ISO calendar system using smart mode will ensure that the day-of-month is from 1 to 31, converting any value beyond the last valid day-of-month to be the last valid day-of-month.

... but you can make it "strict" instead, in which case the parsing fails. Complete example (using u instead of y to avoid the ambiguity of not specifying an era):

import java.time.*;
import java.time.format.*;

public class Test {

    public static void main (String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/uuuu");
        // With the "smart" resolver style, it parses
        System.out.println(formatter.getResolverStyle());
        LocalDate date = LocalDate.parse("9/31/2018", formatter);
        System.out.println(date);

        // But with a strict style...
        formatter = formatter.withResolverStyle(ResolverStyle.STRICT);
        LocalDate.parse("9/31/2018", formatter);
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194