Search code examples
javadatestring-parsinglocaldate

How to correctly parse to LocalDate from String in Java?


I faced a strange issue. I can't parse String value to LocalDate. The problem is that in runtime I paused at breakpoint and execute parsing in evaluate expression tool and it works. But then I continue application and I get an exception with next clause:

Caused by: java.time.format.DateTimeParseException: Text '-218906870-0-9088-15635' could not be parsed at index 11 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400) at com.library.controller.CrudController.returnBook(CrudController.java:96) ... 55 more

My code is here

LocalDate date = returnDatePicker.getValue();
    Journal item = (Journal) tableView.getSelectionModel().getSelectedItem();
    if(date != null && item != null) {
        LocalDate itemDate = LocalDate.parse(item.getStartDate().toString());
        if (date.isAfter(itemDate)) {
            journalDao.saveOrUpdate(item.withReturnDate(date));
            returnPanel.setDisable(true);
            fillJournal();
        }
    }

Date in String value looks like "2017-12-30". A few screenshots: When I evaluate expression I get correct result

How is it even possible? It works in evaluate, and doesn't in runtime. I would really appreciate if you give me a few hints.


Solution

  • Casting a java.util.Date to a String and then parsing that string into a LocalDate might not be the best way to convert a Date into a LocalDate.

    Try the following (explained in more detail here) and see if that fixes your problem:

    Date startDate = item.getStartDate();
    ZoneId zoneId = ZoneId.systemDefault(); // Or ZoneId.of( "Europe/Moscow" ) etc.
    LocalDate itemDate = startDate.toInstant().atZone( zoneId ).toLocalDate();