英文:
MM/yy Date parse issue - Unable to obtain LocalDate from TemporalAccessor
问题
I am trying to convert my date (MM/yy) in String format to LocalDate. However, I get a DateTimeParseException
.
The detailed error is -
j$.time.format.DateTimeParseException: Text '12/34' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=12, Year=2034},ISO of type j$.time.format.Parsed
My code is as following -
val formatter = DateTimeFormatter.ofPattern("MM/yy")
val currentDate = LocalDate.now().format(formatter)
val expiryDate = LocalDate.parse(validityDate, formatter)
val period = Period.between(expiryDate, LocalDate.parse(currentDate, formatter))
val months = period.months
The exception occurs during this code execution -
val expiryDate = LocalDate.parse(validityDate, formatter)
The value of validityDate
is "12/34".
I can't figure out what the issue is.
英文:
I am trying to convert my date (MM/yy) in String format to LocalDate. However, I get a DateTimeParseException
.
The detailed error is -
>
> j$.time.format.DateTimeParseException: Text '12/34' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=12, Year=2034},ISO of type j$.time.format.Parsed
My code is as following -
val formatter = DateTimeFormatter.ofPattern("MM/yy")
val currentDate = LocalDate.now().format(formatter)
val expiryDate = LocalDate.parse(validityDate, formatter)
val period = Period.between(expiryDate, LocalDate.parse(currentDate, formatter))
val months = period.months
The exception occurs during this code execution -
val expiryDate = LocalDate.parse(validityDate, formatter)
The value of validityDate
is "12/34".
I can't figure out what the issue is.
答案1
得分: 0
似乎您没有指定月份中的日期,因此LocalDate
无法解析日期。
val formatter = DateTimeFormatter.ofPattern("dd/MM/yy")
val validityDate = "01/12/34"
val currentDate = LocalDate.now().format(formatter)
val expiryDate = LocalDate.parse(validityDate, formatter)
val period = Period.between(expiryDate, LocalDate.parse(currentDate, formatter))
val months = period.months
我使用上述代码进行了测试,并成功解析了validityDate
。
英文:
It seems that you didn't specify the day in month, so LocalDate
cannot parse the date.
val formatter = DateTimeFormatter.ofPattern("dd/MM/yy")
val validityDate = "01/12/34"
val currentDate = LocalDate.now().format(formatter)
val expiryDate = LocalDate.parse(validityDate, formatter)
val period = Period.between(expiryDate, LocalDate.parse(currentDate, formatter))
val months = period.months
I tested it with the above code and successfully parse the validityDate
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论