gpt4 book ai didi

Java 8 : How to parse expiration date of debit card?

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:18 32 4
gpt4 key购买 nike

用 Joda 时间解析借记卡/信用卡的到期日期真的很容易:

org.joda.time.format.DateTimeFormatter dateTimeFormatter = org.joda.time.format.DateTimeFormat.forPattern("MMyy").withZone(DateTimeZone.forID("UTC"));
org.joda.time.DateTime jodaDateTime = dateTimeFormatter.parseDateTime("0216");
System.out.println(jodaDateTime);

输出:2016-02-01T00:00:00.000Z

我尝试使用 Java Time API 来做同样的事情:

java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("MMyy").withZone(ZoneId.of("UTC"));
java.time.LocalDate localDate = java.time.LocalDate.parse("0216", formatter);
System.out.println(localDate);

输出:

Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=2, Year=2016},ISO,UTC of type java.time.format.Parsed at java.time.LocalDate.from(LocalDate.java:368) at java.time.format.Parsed.query(Parsed.java:226) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ... 30 more

我在哪里犯了错误以及如何解决?

最佳答案

A LocalDate表示日期,由年、月、日组成。如果您没有定义这三个字段,则无法创建 LocalDate。在这种情况下,您正在解析一个月和一年,但没有一天。因此,您无法在 LocalDate 中解析它。

如果日期无关紧要,您可以将其解析为 YearMonth对象:

YearMonth is an immutable date-time object that represents the combination of a year and month.

public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMyy").withZone(ZoneId.of("UTC"));
YearMonth yearMonth = YearMonth.parse("0216", formatter);
System.out.println(yearMonth); // prints "2016-02"
}

然后,您可以通过将此 YearMonth 调整为该月的第一天,将其转换为 LocalDate,例如:

LocalDate localDate = yearMonth.atDay(1);

关于Java 8 : How to parse expiration date of debit card?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133540/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com