【问题标题】:Regex, matcher, and DateTimeParseException: Text '01/08/2018' could not be parsed at index 0正则表达式、匹配器和 DateTimeParseException:无法在索引 0 处解析文本“01/08/2018”
【发布时间】:2018-07-20 21:15:17
【问题描述】:

我从下面的代码中得到了这个问题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 设置为 Date 类型。

【问题讨论】:

  • 您的 mDate.group(1) 以 dd/MM/yyyy 格式返回值,但 yyyyMMddHHmmss 模式被赋予 DateTimeFormatter。它清楚地表明它未能在索引 0 处解析意味着这里的年份(yyyy)。此外,您的输入中没有时间信息,并且日期字段的顺序错误。
  • 谢谢你,我修复了它,是的,我不知道我需要添加小时和分钟,但 asDate 做到了。

标签: java java-8 date-parsing localdate


【解决方案1】:

您不需要同时使用正则表达式 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());

【讨论】:

  • 谢谢你是交换它!并更好地清理该回报。
猜你喜欢
  • 2020-06-10
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
相关资源
最近更新 更多