Search code examples
javajava-8date-parsinglocaldate

Regex, matcher, and DateTimeParseException: Text '01/08/2018' could not be parsed at index 0


I am getting this issue java.time.format.DateTimeParseException: Text '01/08/2018' could not be parsed at index 0 from this code below. Not sure what other options I have to parse a string by using this matcher.

    String dateString = "At 01/08/2018"
    String regex = "At (\\d{2}/\\d{2}/\\d{4})";
    Matcher mDate = Pattern.compile(regex).matcher(dateString);
    if (mDate.find()) {
        DateTimeFormatter fmt = new DateTimeFormatterBuilder()
                .appendPattern("yyyyMMddHHmmss")
                .appendValue(ChronoField.MILLI_OF_SECOND, 2)
                .toFormatter();
        LocalDate localDate = LocalDate.parse(mDate.group(1), fmt);
        order.setDate(asDate(localDate)); 
    } else {
        // fails..
    }
}

public static Date asDate(LocalDate localDate) {
    return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}

The output for example: 2018-01-08T00:00:07 but the tricky part here is dateString doesn't have that time set up so maybe the DateTimeFormatterBuilder might work plus setting the order.setDate is a Date type.


Solution

  • You don’t need both a regular expression and a DateTimeFormatter for checking whether your string format agrees with the expected. You do need the formatter to match the expected input.

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("'At 'MM/dd/uuuu");
        String dateString = "At 01/08/2018";
        try {
            LocalDate localDate = LocalDate.parse(dateString, dateFormatter);
            System.out.println(localDate);
            // order.setDate(asDate(localDate));
        } catch (DateTimeParseException dtpe) {
            // fails..
        }
    

    This prints

    2018-01-08
    

    I believe you intended Jan 8; if you intended 1 Aug, swap MM and dd in the format pattern string.

    PS Your asDate can be implemented slightly more simply, clearly and correctly:

        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());