正则表达式、匹配器和 DateTimeParseException:无法在索引 0 处解析文本“01/08/2018”

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

我从下面的这段代码中得到了这个问题 java.time.format.DateTimeParseException: Text '01/08/2018' could not be parsed at index 0。不确定使用此匹配器解析字符串还有哪些其他选项。

    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());
}

输出例如:2018-01-08T00:00:07 但这里棘手的部分是 dateString 没有设置那个时间所以 DateTimeFormatterBuilder 可能会工作加上设置 order.setDate 是日期类型。

您不需要正则表达式 DateTimeFormatter 来检查您的字符串格式是否符合预期。您确实需要格式化程序来匹配预期的输入。

    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..
    }

这会打印

2018-01-08

我相信你打算在 1 月 8 日;如果您打算在 8 月 1 日,请交换格式模式字符串中的 MMdd

PS你的asDate可以实现的稍微简单一些,清晰正确:

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