java8将日期格式yyyyMM转换为LocalDate
LocalDate: parse yyyy-MM
当我们希望将一个yyyyMM格式的日期转换为LocalDate的时候,不出意外会报错java.time.format.DateTimeParseException因为LocalDate是需要指定到具体的一天的,所以当我们想解析202211这个字符串时因为没有对应的这个月的哪一天,所以运行的时候会报错,导致无法构建LocalDate的实例。
解决方法一
如果你只是想分析了一年一个月,你可以使用YearMonth对象,然后再根据YearMonth对象获取对应月的其中一天:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMM");
YearMonth ym = YearMonth.parse("202211", fmt);
LocalDate dt = ym.atEndOfMonth(); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMM"); YearMonth ym = YearMonth.parse("202211", fmt); LocalDate dt = ym.atEndOfMonth();
解决方法二
但是,如果想直接解析为LocalDate对象,那么就需要自定义一个DateTimeFormatter,在其中指定该月的第一天为默认值:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
LocalDate dt = LocalDate.parse("202011", fmt); DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM") .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) .toFormatter(); LocalDate dt = LocalDate.parse("202011", fmt);
首发链接:
LocalDate: parse yyyy-MM 当我们希望将一个yyyyMM格式的日期转换为LocalDate的时候,不出意外会报错java.time.format.DateTimeParseException因为LocalDate是需要指定到具体的一天的,所以当我们想解析202211这个字符串时因为没有对应的这个月的哪一天,所以运行的时候会报错,导致无法构建LocalDate的实例。 解决方法一 如果你只是想分析了一年一个月,你可以使用YearMonth对象,然后再根据YearMonth对象获取对应月的其中一天: DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMM"); YearMonth ym = YearMonth.parse("202211", fmt); LocalDate dt = ym.atEndOfMonth(); 解决方法二 但是,如果想直接解析为LocalDate对象,那么就需要自定义一个DateTimeFormatter,在其中指定该月的第一天为默认值: DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM") .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) .toFormatter(); LocalDate dt = LocalDate.parse("202011", fmt); 首发链接: