【问题标题】:Java 8: How to parse expiration date of debit card?Java 8:如何解析借记卡的到期日期?
【发布时间】:2016-02-01 14:53:01
【问题描述】:

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

输出:

原因:java.time.DateTimeException:无法获取LocalDate 来自 TemporalAccessor: {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) 在 java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ... 30 更多

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

【问题讨论】:

  • 本地日期似乎不能像您想要的那样广泛。本地需要一天。

标签: java java-8 jodatime java-time


【解决方案1】:

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

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

LocalDate localDate = yearMonth.atDay(1);

【讨论】:

  • 可行的方法 - 虽然在信用卡的情况下可能是 LocalDate expiry = yearMonth.atEndOfMonth();
  • @assylias True 但 OP 的工作示例也计算到本月的第一天。
  • @user471011 是的,但这使用旧的日历/日期类。你现在不应该在 Java 8 中使用它们(除了在不支持 Java Time 的系统上运行)。
  • 不需要.withZone(ZoneId.of("UTC"))
  • @user471011 不一定。您可以使用DateTimeFormatter.parseBest,解析为YearMonthLocalDateTime
猜你喜欢
  • 2016-04-21
  • 1970-01-01
  • 2015-06-26
  • 2017-09-26
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
相关资源
最近更新 更多