YearMonth Expiry Validation
Validate card expiry printed as MM/yy with YearMonth.parse: the printed month stays valid through its last day, so only earlier months count as expired.
Code
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class CardExpiryValidator {
private static final DateTimeFormatter MM_YY = DateTimeFormatter.ofPattern("MM/yy");
static boolean isExpired(String printed, YearMonth today) {
try {
YearMonth expiry = YearMonth.parse(printed, MM_YY);
// 有效期覆盖整月:到期月最后一天前都可用
return expiry.isBefore(today);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("bad expiry: " + printed, e);
}
}
public static void main(String[] args) {
YearMonth today = YearMonth.of(2026, 11);
for (String card : new String[] {"11/26", "12/26", "10/26"}) {
System.out.println(card + " -> " + (isExpired(card, today) ? "expired" : "valid"));
}
}
}How the snippet works
The code’s whole job belongs to the class CardExpiryValidator and the functions isExpired and main.
Repetition is confined to for (String card : new String[] {"11/26", "12/26", "10/26"}) — the rest of the file is straight-line. IllegalArgumentException is the guard’s signal — thrown at the branch, before any partial work happens.
Applying it
Entry signature: static boolean isExpired(String printed, YearMonth today)
Execute the file and main walks through isExpired, in that order.
Statements that matter
throw new IllegalArgumentException("bad expiry: " + printed, e);
return expiry.isBefore(today);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does the snippet do with malformed data?
- It throws `IllegalArgumentException` before any real work runs — handle it at the call site or let it propagate deliberately.
- How do you run YearMonth Expiry Validation?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.