【问题标题】:java.time.format.DateTimeParseException: Text '2016-2-2' could not be parsed at index 5java.time.format.DateTimeParseException:无法在索引 5 处解析文本“2016-2-2”
【发布时间】:2016-03-09 12:47:47
【问题描述】:

我正在尝试从import java.time.LocalDate; 创建LocalDate 的实例 我关注this

这是我的代码:

     LocalDate sd=  LocalDate.parse("2016-2-2");

我遇到了错误:

java.time.format.DateTimeParseException: Text '2016-2-2' could not be parsed at index 5
    at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)

在另一个尝试创建LocalDate 的实例时,我尝试了

LocalDate ed=  new LocalDate("2016-2-4");

但它再次抱怨:

The constructor LocalDate(String) is undefined

【问题讨论】:

  • 您提供的链接是关于org.joda.time.LocalDate 而不是java.time.LocalDate

标签: java date


【解决方案1】:

您需要使用格式化程序来解析 java.time.LocalDate 的单字符日/月字段

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
LocalDate date = LocalDate.parse("2016-2-2", formatter);

【讨论】:

    【解决方案2】:

    LocalDate 根本无法解析该字符串。请改用 SimpleDateFormat:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    【讨论】:

    • LocalDate 可以解析那个字符串,建议使用过时的类不是很有帮助。
    猜你喜欢
    • 2021-12-23
    • 2021-11-03
    • 1970-01-01
    • 2021-09-10
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2020-06-25
    相关资源
    最近更新 更多