为什么我的模式(“yyyyMM”)无法使用DateTimeFormatter进行解析(java 8) [英] Why my pattern("yyyyMM") cannot parse with DateTimeFormatter (java 8)

查看:1955
本文介绍了为什么我的模式(“yyyyMM”)无法使用DateTimeFormatter进行解析(java 8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 SimpleDateFormat 时,它可以解析。

When I using SimpleDateFormat, it can parse.

SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
format.setLenient(false);
Date d = format.parse(date);

但是当我使用Java 8 DateTimeFormatter 时,

But When I use Java 8 DateTimeFormatter,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = LocalDate.parse(date, formatter);

它抛出


java.time.format.DateTimeParseException:无法解析文本'201510':无法从TemporalAccessor获取LocalDate:{Year = 2015,MonthOfYear = 10},类型为java
.time.format的ISO。解析

java.time.format.DateTimeParseException: Text '201510' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2015, MonthOfYear=10},ISO of type java .time.format.Parsed

日期的字符串值为201510

推荐答案

问自己一个问题:哪一天应该用字符串201510解析? LocalDate 需要一天,但由于要解析的日期没有日期, LocalDate 的实例不能

Ask yourself the question: which day should be parsed with the String "201510"? A LocalDate needs a day but since there is no day in the date to parse, an instance of LocalDate can't be constructed.

如果您只想解析一年零一个月,可以使用 YearMonth 对象:

If you just want to parse a year and a month, you can use the YearMonth object instead:

YearMonth localDate = YearMonth.parse(date, formatter);

但是,如果你真的想拥有 LocalDate 要从此String中解析,您可以构建自己的 DateTimeFormatter ,以便它将该月的第一天用作默认值:

However, if you really want to have a LocalDate to be parsed from this String, you can build your own DateTimeFormatter so that it uses the first day of the month as default value:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                .appendPattern("yyyyMM")
                                .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                                .toFormatter();
LocalDate localDate = LocalDate.parse(date, formatter);

这篇关于为什么我的模式(“yyyyMM”)无法使用DateTimeFormatter进行解析(java 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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