Home » Java » java.time.format.DateTimeParseException: Text '13.05.2018' could not be parsed at index 2

java.time.format.DateTimeParseException: Text '13.05.2018' could not be parsed at index 2

Posted by: admin June 30, 2018 Leave a comment

Questions:

I have a websocket that receives requests from clients as JSON strings. One of the requests I receive contains a date. I am retrieving the date as a String but I am unable to change it to LocalDate. This is the JSON request I receive {"type":"dataRequest","startDate":"13.05.2018","endDate":"20.05.2018","interval":"01:01:01"}

I am using Google's GSON to parse the JSON.

This is the Java code I am using to get the date as a String and to parse it as LocalDate.

private List<LocalDate> getStartEndDate(String message){

        List<LocalDate> dates = new ArrayList();
        JsonObject obj = parseJson(message);
        JsonPrimitive date = obj.getAsJsonPrimitive("startDate");
        String dateString = date.toString();
        DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd.MM.yyyy");
        dates.add(LocalDate.parse(dateString, formater));
        date = obj.getAsJsonPrimitive("endDate");
        dateString = date.getAsString();
        LocalDate end = LocalDate.parse(dateString, formater);
        dates.add(end);

        return dates;
    }
Answers: