Pre*_*thi 2 java regex validation date
我希望以MM/YY格式验证信用卡到期日期.我不知道如何验证,是否采用简单日期格式/正则表达式.
感谢您的帮助.
Boh*_*ian 15
使用SimpleDateFormat来解析Date,然后将它与一个新的比较Date,这是"现在":
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());
Run Code Online (Sandbox Code Playgroud)
感谢@ryanp宽大的方面.ParseException如果输入不正确,上面的代码现在将抛出一个.
扮演魔鬼的拥护者......
boolean validateCardExpiryDate(String expiryDate) {
return expiryDate.matches("(?:0[1-9]|1[0-2])/[0-9]{2}");
}
Run Code Online (Sandbox Code Playgroud)
翻译为:
...所以这个版本需要零填充月(01 - 12).?在第一个之后添加一个0以防止这种情况.