Java 8:如何解析借记卡的到期日期?

use*_*011 6 java jodatime java-8 java-time

使用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);
Run Code Online (Sandbox Code Playgroud)

日期: 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);
Run Code Online (Sandbox Code Playgroud)

输出:

引起:java.time.DateTimeException:无法从TemporalAccessor获取LocalDate:{MonthOfYear = 2,Year = 2016},ISO,UTC,类型为java.time.format.Parsed,类型为java.time.LocalDate.from(LocalDate.java :368)java.time.format.Parsed.query(Parsed.java:226)at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)... 30 more

我犯了什么错误以及如何解决它?

Tun*_*aki 13

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

如果这一天无关紧要,您可以将其解析为一个YearMonth对象:

YearMonth 是一个不可变的日期时间对象,表示年和月的组合.

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"
}
Run Code Online (Sandbox Code Playgroud)

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

LocalDate localDate = yearMonth.atDay(1);
Run Code Online (Sandbox Code Playgroud)

  • 要走的路 - 虽然在信用卡的情况下,它可能是`LocalDate expiry = yearMonth.atEndOfMonth();`. (8认同)
  • @assylias是的但是OP的工作示例也评估到了本月的第一天. (3认同)
  • @ user471011是的但是它使用旧的Calendar/Date类.您现在不应该使用Java 8(除非使用不支持Java Time的系统). (3认同)
  • 不需要`.withZone(ZoneId.of("UTC"))`. (2认同)
  • @ user471011不一定.您可以使用`DateTimeFormatter.parseBest`,解析为`YearMonth`或`LocalDateTime` (2认同)