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

标签 java java-8 jodatime 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);

输出: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);

输出:

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

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

最佳答案

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

关于Java 8 : How to parse expiration date of debit card?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133540/

相关文章:

java - AngularJS - Java EE REST 安全性

android - 从两个日期中找到月份和日期的差异

java - 查找小时范围是否重叠(无论日期如何)

java - 无法获取客户的费用 list

java - 尝试在聊天事件(Minecraft、Spigot)上设置玩家显示名称时出错

java - 如何在不实现 Serializable 接口(interface)的情况下序列化/反序列化对象?

java - 标准 Kotlin 库中有哪些 Java 8 Stream.collect 等效项?

java - 在强制转换表达式中使用 AdditionalBound

java-8 - 对象消息上的 JMS 消息选择器

java - 优化 Joda Time 中的许多间隔