java.time.format.DateTimeParseException:Text' 2016-2-2'无法在索引5处解析

时间:2016-03-08 21:41:29

标签: java date

我正在尝试从LocalDate创建import java.time.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

2 个答案:

答案 0 :(得分:5)

您需要使用格式化程序来解析java.time.LocalDate

的单个字符日/月字段
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
LocalDate date = LocalDate.parse("2016-2-2", formatter);

答案 1 :(得分:-6)

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