Why my pattern(“yyyyMM”) cannot parse with DateTimeFormatter (java 8)

ぐ巨炮叔叔 提交于 2019-11-30 05:39:28

问题


When I using SimpleDateFormat, it can parse.

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

But When I use Java 8 DateTimeFormatter,

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

it throws

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

String value for date is "201510".


回答1:


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.

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

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

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);



回答2:


You can use a YearMonth and specify the day you want (say the first for example):

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

Or if the day is irrelevant, just use a YearMonth.



来源:https://stackoverflow.com/questions/34061759/why-my-patternyyyymm-cannot-parse-with-datetimeformatter-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!