[英]validate the credit card expiry date using java?
我希望以MM / YY格式驗證信用卡到期日期。 我不知道如何驗證,是否采用簡單日期格式/正則表達式。
感謝您的幫助。
使用SimpleDateFormat
解析Date
,然后將其與新的Date
進行比較,即“now”:
String input = "11/12"; // for example
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/yy");
simpleDateFormat.setLenient(false);
Date expiry = simpleDateFormat.parse(input);
boolean expired = expiry.before(new Date());
感謝@ryanp
的寬大方面。 如果輸入不正確,上面的代碼現在將拋出ParseException
。
扮演魔鬼的擁護者......
boolean validateCardExpiryDate(String expiryDate) {
return expiryDate.matches("(?:0[1-9]|1[0-2])/[0-9]{2}");
}
翻譯為:
...所以這個版本需要零填充月(01 - 12)。 加一個?
在第0
之后防止這種情況發生。
你真的需要使用正則表達式嗎? 正則表達式實際上只適用於匹配字符,而不是日期。 我認為使用簡單的日期函數會容易得多。
我認為代碼會更好:
int month = 11;
int year = 2012;
int totalMonth = (year * 12) + month;
totalMonth++; // next month needed
int nextMonth = totalMonth % 12;
int yearOfNextMonth = totalMonth / 12;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/yyyy");
simpleDateFormat.setLenient(false);
Date expiry = simpleDateFormat.parse(nextMonth + "/" + yearOfNextMonth);
boolean expired = expiry.before(new Date());
您需要在下個月計算,因為信用卡上顯示的月份是卡有效的最后一個月。
要驗證您是否擁有有效的到期日期字符串:
DateTimeFormatter ccMonthFormatter = DateTimeFormatter.ofPattern("MM/uu");
String creditCardExpiryDateString = "11/21";
try {
YearMonth lastValidMonth = YearMonth.parse(creditCardExpiryDateString, ccMonthFormatter);
} catch (DateTimeParseException dtpe) {
System.out.println("Not a valid expiry date: " + creditCardExpiryDateString);
}
驗證它是否表示過期的信用卡:
if (YearMonth.now(ZoneId.systemDefault()).isAfter(lastValidMonth)) {
System.out.println("Credit card has expired");
}
考慮您要使用的時區,因為新月份並非在所有時區的同一時刻開始。 如果你想要UTC:
if (YearMonth.now(ZoneOffset.UTC).isAfter(lastValidMonth)) {
如果你想,為了這個例子,歐洲/基輔時區:
if (YearMonth.now(ZoneId.of("Europe/Kiev")).isAfter(lastValidMonth)) {
鏈接: Oracle教程:日期時間,解釋如何使用java.time。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.