2016-02-01 29 views
5

这是很容易解析借记卡/信用卡的有效期限与乔达时间:Java 8:如何解析借记卡的到期日期?

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

输出:

引起:java.time.DateTimeException:Unabl e以获得来自TemporalAccessor的LocalDate :{MonthOfYear = 2,Year = 2016},ISO, 类型的UTC,时间格式为 java.time.LocalDate.from(LocalDate.java:368)at java .time.format.Parsed.query(Parsed.java:226)在 java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ...... 30多个

当我犯了一个错误以及如何解决它?

+0

这似乎是一个本地日期不能是为广泛的一个字段你有想要的。本地需要一天的时间。 – Fallenreaper

回答

10

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" 
} 

然后,您可以通过它调整到每月的第一天例如改变这个YearMonthLocalDate

LocalDate localDate = yearMonth.atDay(1); 
+6

要走的路 - 尽管在信用卡的情况下,它可能是LocalDate expiry = yearMonth.atEndOfMonth();'。 – assylias

+3

@assylias正确,但OP的工作示例也评估到本月的第一个月。 – bowmore

+0

@Tunaki或:Date date = new SimpleDateFormat(“MMyy”)。parse(“1016”); LocalDate localDate = LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault())。toLocalDate(); – user471011