使用Joda time解析借记/信用卡的过期日期非常容易:
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);
输出:
异常原因:java.time.DateTimeException: 无法从 TemporalAccessor 中获取 LocalDate:{MonthOfYear=2, Year=2016},ISO,UTC; 类型为 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
我犯了什么错误,应该如何解决?