Java 8 DataTime解析错误 [英] java 8 datatime parse error

查看:91
本文介绍了Java 8 DataTime解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为LocalDate对象.但出现以下错误.

I am trying to convert a string to LocalDate object. but I get the following error.

private LocalDate getLocalDate(String year) {
        String yearFormatted = "2015-01-11";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");
        LocalDate dateTime = LocalDate.parse(yearFormatted, formatter);
        return  dateTime;
    }

这是错误

Caused by: java.time.format.DateTimeParseException: Text '2015-01-11' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=11, WeekBasedYear[WeekFields[SUNDAY,1]]=2015, MonthOfYear=1},ISO of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920) ~[na:1.8.0_102]
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855) ~[na:1.8.0_102]
    at java.time.LocalDate.parse(LocalDate.java:400) ~[na:1.8.0_102]

推荐答案

文档说,格式格式中的大写字母Y是基于周的年份,即周编号所属的年份.这并不总是与日历年相同(尽管通常是这样). Java足够聪明,可以识别出它不能确定从基于星期的年,月和日中获取日期,因此它抛出异常.

As the documentation says, the capital Y in a format pattern is for week-based-year, that is, the year that the week number belongs to. This is not always the same as the calendar year (though most often it is). Java is smart enough to recognize that it cannot be sure to get a date out of week-based year, month and day-of-month, so it throws the exception instead.

由于字符串的格式与默认的LocalDate格式(ISO 8601)一致,所以最简单的解决方案是完全删除格式化程序,然后执行以下操作:

Since the format of your string agrees with the default LocalDate format (ISO 8601), the simplest solution is to drop the formatter completely and just do:

    LocalDate dateTime = LocalDate.parse(yearFormatted);

进行此更改后,您的方法将返回我认为您期望的日期2015-01-11.另一个解决方法是将YYYY替换为小写字母yyyy表示年份,或者将uuuu替换为签名年份(0表示1 BC,-1表示2BC,等等).

With this change, you method returns a date of 2015-01-11 as I think you had expected. Another fix is to replace YYYY with either lowercase yyyy for year-of-era or uuuu for a signed year (where 0 is 1 BC, -1 is 2BC, etc.).

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

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