regex date validation for yyyyMMdd
I'm looking for a regex string that will validate dates formatted as yyyyMMdd (no delimiters) and works for leap years. The closest thing I found so far only validates dates since 2000.
import java.util.regex.Pattern;
public class TestDate {
public static final Patter开发者_开发知识库n datePattern = Pattern.compile("** Need RegEx **");
public static void main(String[] args) {
System.out.println(datePattern.matcher("19960229").matches());
}
}
I suggest using the java.text.DateFormat
as shown in this page :
public static boolean isValidDateStr(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.setLenient(false);
sdf.parse(date);
}
catch (ParseException e) {
return false;
}
catch (IllegalArgumentException e) {
return false;
}
return true;
}
I thing using regex for this is almost impossible, due to the complex calculation required for leap years. Jon Skeet is right: use new SimpleDateFormat("yyyyMMdd")
for this.
the regex for a leap year is very complex: case in point: (this also incorporates full date checking)
"(((\\d\\d)(0[48]|[2468][048]|[13579][26])|([02468][048]|[13579][26])(00))(02)([012]\\d))|(\\d\\d([02468][1235679]|[13579][01345789])(02)([01]\\d|2[012345678]))|(\\d\\d\\d\\d((0[13578]|1[02])([012]\\d|3[01])|((0[46]|11)([012]\\d|30))))"
first section separates out the the general case with non ending on 00
the second section handles the century year so only years divisable by 400 are leap years (1900 is not a leap year)
then in the last section it handles all the other months
(I didn't really test this but it should work close enough)
精彩评论