无法解析最近格式化的ZonedDateTime Java 8 [英] Cant parse recently formatted ZonedDateTime Java 8

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

问题描述

为什么使用此代码

DateTimeFormatter SENT_DATE_FORMATTER = DateTimeFormatter.ofPattern("E, d MMM YYYY HH:mm:ss Z", Locale.US);
ZonedDateTime now = ZonedDateTime.now();
String dateStr = now.format(SENT_DATE_FORMATTER);
System.out.println(dateStr);

ZonedDateTime zoned = ZonedDateTime.parse(dateStr, SENT_DATE_FORMATTER);

在sysout行上打印正确的日期,但抛出DateTimeParseException(无法从TemporalAccessor获取ZonedDateTime)

Prints the correct date on the sysout line but throws a DateTimeParseException (Unable to obtain ZonedDateTime from TemporalAccessor) on the parse line?

推荐答案

大写的Y代表基于周的年,请参见 javadoc 。为了使解析器正常工作,您需要将其更改为年份(u)或时代(y)。然后,解析器可以创建日历年,月(M)和月日(d)之外的日期。请记住,以周为基础的年份可以与上一个或下一个日历年相关,如果您的月份和日期接近日历年的开始或结束,则不是实际的年份。因此,不可能仅将基于周的年份与日历年份相等! 并且没有精确定义的日历年,就无法形成日期。

Capitalized Y stands for week-based-year, see javadoc. In order to make the parser working you rather need to change it to year (u) or year-of-era (y). Then the parser can create a date out of calendar year, month (M) and day-of-month (d). Keep in mind that the week-based-year can relate to previous or next calendar year, not the actual one if your month and day-of-month are near the start or end of calendar year. Therefore it is not possible to just equalize the week-based-year to the calendar year! And without a precisely defined calendar year it is not possible to form a date.

否则,如果您有星期几,基于模式的年(w),那么解析器将能够理解输入,因为基于周的年(Y),基于周的周年(w)和周中的某天(E)还会对日期进行可解释的组合。

Otherwise, if you had the week-of-week-based-year (w) in your pattern, too, then your parser would be able to understand the input because week-based-year (Y), week-of-week-based-year (w) and day-of-week (E) would also make an interpretable combination for a date.

但是请注意,输入中与您的模式匹配的所有给定细节必须一致(例如2015-08 -31是星期一,而不是星期二),否则解析器会再次抱怨(至少在严格模式下如此)。

Note however, that all given details in the input matching your pattern must be consistent (for example 2015-08-31 is Monday and not Tuesday) otherwise the parser will complain again (at least in strict mode).

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

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