【问题标题】:Parsing "1-11-2022" into LocalDate throws DateTimeParseException in Java [duplicate]将 \"1-11-2022\" 解析为 LocalDate 在 Java 中抛出 DateTimeParseException [重复]
【发布时间】:2022-11-21 02:00:12
【问题描述】:

我在从 txt 读取日期部分并将它们定义为对象中的 localdate 时遇到问题。

以下是 txt 文件中的示例值。

1-11-2022
11-10-2022
3-12-2022
...

这是下面显示的代码 sn-ps。

static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
...
object.setDate(LocalDate.parse(objectValue[0], formatter));  // HERE IS ERROR
...

这是下面显示的错误。

Exception in thread "main" java.time.format.DateTimeParseException: Text '1-11-2022' could not be parsed at index 0

我该如何解决?

【问题讨论】:

  • 我现在没有时间检查这个,因此不是答案:但是你已经按照要求的格式写了“dd”;我认为这意味着输入时至少需要两位数字。

标签: java date localdate


【解决方案1】:

正如documentation of DateTimeFormatter中所指定的那样,dd表示预期的最小位数是两位,并且您的字符串中需要有一个前导零(即1 -> 013 -> @ 987654327@) 以使此格式化模式起作用。

数字:

如果字母数是一个,然后使用最小位数没有填充.否则,位数用作输出字段的宽度,其中价值 必要时补零.

相反,您可以使用模式 "d-MM-yyyy",它能够解析 "3-12-2022""11-10-2022"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-17
    • 2022-12-22
    • 2019-10-27
    • 1970-01-01
    • 2018-09-27
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多