DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy");
LocalDate parsedDate = LocalDate.parse(entryOne.getKey(), dateFormat)
获取异常
Text '03/2018' could not be parsed: Unable to obtain LocalDate from TemporalAccessor:
如何使用具有默认月份第一天的 Java 8 解析此字符串并转换为日期。我们使用的东西。
TemporalAdjusters.firstDayOfMonth()
最佳答案
将 MM/yyyy
字符串转换为 LocalDate
时,您有两种选择:
解析为
YearMonth
,然后转换为LocalDate
:String date = "04/2018"; DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy"); YearMonth yearMonth = YearMonth.parse(date, dateFormat); LocalDate parsedDate = yearMonth.atDay(1); System.out.println(parsedDate); // prints: 2018-04-01
使用定义了默认月份日期的
DateTimeFormatter
:String date = "04/2018"; DateTimeFormatter dateFormat = new DateTimeFormatterBuilder() .appendPattern("MM/yyyy") .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) .toFormatter(); LocalDate parsedDate = LocalDate.parse(date, dateFormat); System.out.println(parsedDate); // prints: 2018-04-01
关于java - 字符串中的月年至今 Java 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50106376/