0

Java 1.8

Date format "dd.MM.yyyy"

Correct example is : 30.03.2020".

Snippet:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;\

DateTimeFormatter formatter = DateTimeFormatter
                        .ofPattern("dd.MM.yyyy")
                        .withResolverStyle(ResolverStyle.LENIENT);
                return LocalDate.parse(dateAsString, formatter);

But when I input INCORRECT date:

35.02.2020

But my code not throw error. And return date 2020-03-05

Why?

Alexei
  • 14,350
  • 37
  • 121
  • 240
  • Is this the answer you're looking for? [Answer for 'How to sanity check a date in Java'](https://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java/39649815#39649815). Or are you asking ___why___ there are these modes? Or Something else? – Ivo Mori May 28 '20 at 00:15

1 Answers1

2

Try to replace ResolverStyle.LENIENT mode with STRICT. Check docs for more details

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
slesh
  • 1,902
  • 1
  • 18
  • 29
  • I get error when input CORRECT date (30.03.2020), error: java.time.format.DateTimeParseException: Text '30.03.2020' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=3, YearOfEra=2020, DayOfMonth=30},ISO of type java.time.format.Parsed – Alexei May 28 '20 at 10:47
  • 1
    Interesting, it's turned out that you need to specify year as "uuuu" when you use SMART mode, because yyyy is year-of-era. Or you may set SMART mode which is used by default. – slesh May 28 '20 at 11:01
  • After change to "dd.MM.uuuu" with ResolverStyle.STRICT the error is gone – Alexei May 28 '20 at 11:16
  • Yeah, strict mode it too strict, hah. I'd suggest you use SMART which is a bit more intuitive. – slesh May 28 '20 at 11:27