无法解析String到LocalDate(Java 8) [英] Can't parse String to LocalDate (Java 8)

查看:428
本文介绍了无法解析String到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:


引起:java.time.DateTimeException:无法从中获取LocalDate TemporalAccessor:{DayOfMonth = 1,MonthOfYear = 7,WeekBasedYear [WeekFields [MONDAY,4]] = 2015},ISO类型为java.time.format.Parsed

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.

这篇关于无法解析String到LocalDate(Java 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆