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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.