Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It is really easy to parse expiration date of debit/credit card with 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);

Out: 2016-02-01T00:00:00.000Z

I tried to do the same but with 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);

Output:

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

Where I made a mistake and how to resolve it?

like image 555
user471011 Avatar asked Feb 01 '16 14:02

user471011


People also ask

How do I set the expiry date in Java?

DAYS); Date expiry = new Date(System. currentTimeMillis() + year); System. out. println(expiry);

How to write expiry date of card?

Expiration dates appear on the front or back of a credit card in a two-digit month/year format. Credit cards expire at the end of the month written on the card. For example, a credit card's expiration date may read as 11/24, which means the card is active through the last day of November 2024.

How do I enter my credit card expiration date online?

In short, all financial transaction cards should show the card's expiration date in one of the following two formats: “MM / YY” or “MM-YY” — with the first being the by far most common for credit cards. This represents two digits for the month and two for the year — for example, “02 / 24”.


1 Answers

A LocalDate represents date that is composed of a year, a month and a day. You can't make a LocalDate if you don't have those three fields defined. In this case, you are parsing a month and a year, but there is no day. As such, you can't parse it in a LocalDate.

If the day is irrelevant, you could parse it into a YearMonth object:

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

You could then transform this YearMonth into a LocalDate by adjusting it to the first day of the month for example:

LocalDate localDate = yearMonth.atDay(1);
like image 192
Tunaki Avatar answered Sep 16 '22 13:09

Tunaki