Kotlin如何解析MM/yy格式日期字符串?缺失日值怎么办?
解析MM/yy格式字符串为Kotlin日期对象的解决方案
问题说明
如何将MM/yy格式(例如12/22)的字符串解析为Kotlin的日期对象?没有日值的情况下能否存在日期对象?
尝试的代码如下:
import java.time.LocalDate import java.util.Locale import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatterBuilder fun main() { var str_date = "06/22" val df: DateTimeFormatter = DateTimeFormatterBuilder() .appendPattern("MM/yy") .toFormatter(Locale.ENGLISH); println(LocalDate.parse(str_date, df)) }
运行后抛出异常:
java.time.format.DateTimeParseException: Text '06/22' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2022, MonthOfYear=6},ISO of type java.time.format.Parsed
核心原因
LocalDate是代表完整日期的对象,必须包含年、月、日三个核心字段,仅提供年月信息无法构造出合法的LocalDate,这就是报错的根本原因。
解决方案
方案1:解析时补充默认日值
通过DateTimeFormatterBuilder指定默认的日字段值(比如每月第一天),让解析器能构造完整的LocalDate:
import java.time.LocalDate import java.util.Locale import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatterBuilder import java.time.temporal.ChronoField fun main() { val strDate = "06/22" val formatter = DateTimeFormatterBuilder() .appendPattern("MM/yy") .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) // 设置默认日为每月1号 .toFormatter(Locale.ENGLISH) val localDate = LocalDate.parse(strDate, formatter) println(localDate) // 输出:2022-06-01 }
方案2:先解析为YearMonth再转LocalDate
如果不需要提前指定默认日,可以先将字符串解析为仅包含年月信息的YearMonth对象,之后再根据业务需求补充日值生成LocalDate:
import java.time.YearMonth import java.util.Locale import java.time.format.DateTimeFormatter fun main() { val strDate = "06/22" val formatter = DateTimeFormatter.ofPattern("MM/yy", Locale.ENGLISH) val yearMonth = YearMonth.parse(strDate, formatter) // 转换为当月第一天的LocalDate val firstDayOfMonth = yearMonth.atDay(1) println(firstDayOfMonth) // 输出:2022-06-01 // 转换为当月最后一天的LocalDate val lastDayOfMonth = yearMonth.atEndOfMonth() println(lastDayOfMonth) // 输出:2022-06-30 }
总结
- 没有日值的情况下,无法直接创建
LocalDate对象,因为它要求完整的年、月、日信息。 - 可以通过指定默认日或先解析为
YearMonth再转换两种方式实现需求。
内容的提问来源于stack exchange,提问作者Nivlem
相关产品推荐
相关产品推荐

