Java 8:如何解析借记卡有效期?

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

用 Joda 时间解析 debit/credit 卡的到期日期真的很容易:

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 时间 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

哪里出错了,如何解决?

一个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);