1

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
user2537246
  • 143
  • 2
  • 10
  • your `mDate.group(1)` returns value in dd/MM/yyyy format but yyyyMMddHHmmss pattern is given to DateTimeFormatter. It clearly shows it failed to parse at index 0 means here year (yyyy). Also there is no time information in your input and order of date fields are wrong. – sanit Feb 10 '18 at 06:00
  • thank you i fixed it and yes didn't know i needed to add hours and minutes but the asDate did that trick. – user2537246 Feb 10 '18 at 15:43

1 Answers1

2

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());
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161