【问题标题】:java.time.format.DateTimeParseException: Text '2020052' could not be parsed at index 0java.time.format.DateTimeParseException:无法在索引 0 处解析文本“2020052”
【发布时间】:2020-10-19 23:31:23
【问题描述】:

我正在尝试使用“yyyyMMd”格式使用 DateTimeFormatter 解析“2020052”,但它会引发错误(标题),使用“yyyyMMdd”会引发java.time.format.DateTimeParseException: Text '2020052' could not be parsed at index 6,有谁知道解决方案(除了在前面2,我正在解析一个包含许多日期的大型数据集),下面是我的代码

val format = DateTimeFormatterBuilder().appendPattern("yyyyMMdd").toFormatter()
date = LocalDate.parse("2020052", format)

【问题讨论】:

  • 您在 "2020052" 中的数字太少,无法用 "yyyyMMdd" 解析它 - 您需要两位数的月份和日期:2020 05 02 — 我不确定您为什么会得到使用"yyyyMMd" 时出现异常
  • 这行得通,虽然我不确定为什么:SimpleDateFormat format = new SimpleDateFormat("yyyyMMd"); Date date = format.parse("2020052");

标签: java datetime kotlin


【解决方案1】:
    DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
            .appendValue(ChronoField.YEAR, 4)
            .appendValue(ChronoField.MONTH_OF_YEAR, 2)
            .appendValue(ChronoField.DAY_OF_MONTH, 1)
            .toFormatter();
    System.out.println(LocalDate.parse("2020052", dateFormatter));

输出:

2020-05-02

显然,它只适用于每个月前 9 天内的日期。

【讨论】:

    【解决方案2】:

    获取 7 或 8 个字符的 LocalDate 的通用方法。 String dateString = "20200525";

        if (dateString.length() > 6 && dateString.length() <= 8) {
            LocalDate dateObj = LocalDate.of(Integer.valueOf(dateString.substring(0, 4)),
                    Integer.valueOf(dateString.substring(4, 6)), Integer.valueOf(dateString.substring(6)));
        }
    

    【讨论】:

    • 无论月份中的日期是 1 位还是 2 位数字(只要月号始终是 2 位数字),这都应该有效。
    猜你喜欢
    • 2018-04-04
    • 2018-12-12
    • 2020-06-25
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多