java.time.format.DateTimeParseException:无法在索引 5 处解析文本“2016-2-2”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35878574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:41:55  来源:igfitidea点击:

java.time.format.DateTimeParseException: Text '2016-2-2' could not be parsed at index 5

javadate

提问by Salman Lashkarara

I am trying to make an instance of LocalDatefrom import java.time.LocalDate;and i follow this

我正在尝试创建一个实例LocalDatefromimport java.time.LocalDate;并且我遵循这个

and here is my code:

这是我的代码:

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

and i faced with the error:

我遇到了错误:

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


In another try to make an instance of LocalDate, i tried

在另一个尝试做一个实例的时候LocalDate,我试过

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

but it again complains:

但它再次抱怨:

The constructor LocalDate(String) is undefined

回答by Reimeus

You need to use a formatter to parse single character day/month fields for java.time.LocalDate

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

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

回答by Sason Ohanian

LocalDate simply can't parse that string. Use SimpleDateFormat instead: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

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