无法将字符串解析为 LocalDate (Java 8) [英] Can't parse String to LocalDate (Java 8)
问题描述
我的输入是 2015 年 7 月 1 日格式为01-07-2015"的日期的字符串表示形式.我正在尝试将其解析为 java.time.LocalDate
变量:
My input is a String representation of a date in the format "01-07-2015" for July 1, 2015. I'm trying to parse this into a java.time.LocalDate
variable:
final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-YYYY");
final String input = "01-07-2015";
final LocalDate localDate = LocalDate.parse(input, DATE_FORMAT);
基于 DateTimeFormatter
JavaDoc,我希望这能奏效.但是,我收到了一条非常友好且乐于助人的消息:
Based on the DateTimeFormatter
JavaDoc, I would expect this to work. However, I'm greeted with a very friendly and helpful message:
Caused by: java.time.DateTimeException: Unable to get LocalDate from TemporalAccessor: {DayOfMonth=1, MonthOfYear=7, WeekBasedYear[WeekFields[MONDAY,4]]=2015},java.time.format 类型的 ISO.解析
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=1, MonthOfYear=7, WeekBasedYear[WeekFields[MONDAY,4]]=2015},ISO of type java.time.format.Parsed
我真的不明白这个异常告诉我什么.谁能解释一下出了什么问题?
I don't really understand what this exception is telling me. Can anyone explain me what's going wrong?
推荐答案
一年你必须使用小写的 y:
For year you have to use the lowercase y:
final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy");
大写 Y 用于表示星期.有关详细信息,请参阅 DateTimeFormatter 的 javadoc.
Uppercase Y is used for weekyear. See the javadoc of DateTimeFormatter for more details.
这篇关于无法将字符串解析为 LocalDate (Java 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!