MM/yy日期解析问题 – 无法从TemporalAccessor获取LocalDate。

huangapple go评论108阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年8月4日 23:13:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定