Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalDate DateTimeFormatter problems

Tags:

java

localdate

I have read the manuals and I'm completely at a loss as to why this code does not work.

    // Date Entered must be valid
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy")
            .withResolverStyle(ResolverStyle.STRICT);

    try {
        String dateEntered = lossDateMonth + "/" + lossDateDay + "/" + lossDateYear; // Slash to match UI

        System.out.println(dateEntered);
        LocalDate dateParsed = LocalDate.parse(dateEntered, dateTimeFormatter);

The println statement prints: 07/29/2015

The last line throws an exception: java.time.format.DateTimeParseException: Text '07/29/2015' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {YearOfEra=2015, DayOfMonth=29, MonthOfYear=7},ISO of type java.time.format.Parsed

I read the manual on this and it says this sort of thing happens if you try to resolve a date that does not exist, for example September 31st. Even in the error, the parser seems to understand that I am asking about July 29, 2015, so what am I doing wrong here?

like image 643
user1445967 Avatar asked Jun 15 '26 19:06

user1445967


1 Answers

Replace the pattern "MM/dd/yyyy" by "MM/dd/uuuu". Have a look in DateTimeFormatter and IsoChronology. The problem is that when using .withResolverStyle(ResolverStyle.STRICT) the formatter expects an unique identifier to the year which is provided by uuuu where yyyy is the year of era. This is to strictly validate the values. The uniqueness is given by the fact that uuuu can be negative.

Have a look here, here and here for related posts.

like image 68
akuzminykh Avatar answered Jun 18 '26 09:06

akuzminykh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!