regex date validation for yyyyMMdd

后端 未结 3 1865
隐瞒了意图╮
隐瞒了意图╮ 2021-01-15 05:32

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 dat

相关标签:
3条回答
  • 2021-01-15 06:16

    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.

    0 讨论(0)
  • 2021-01-15 06:20

    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;
      }
    
    0 讨论(0)
  • 2021-01-15 06:21

    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)

    0 讨论(0)
提交回复
热议问题