Home » Java » java – Is there any regex pattern available to check the date format?-Exceptionshub

java – Is there any regex pattern available to check the date format?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a custom date parser which parses the date as per the date format passed by the user. I wanted to check if the input itself conforms to the standard date pattern – ddDD/mmMM/yyyyYYYY h:m:s and the separators can be ‘/’ or ‘.’.

private boolean isDateFormatValid(String dateValue, String dateFormat){
    if(StringUtils.isEmpty(dateValue))
      return false;
    else
      dateValue = StringUtils.replace(dateValue,"/","-");

    dateFormat = StringUtils.isEmpty(dateFormat) ? "dd-MM-yyyy" : StringUtils.replaceEach(dateFormat,
        new String[]{"/", "DD", "YYYY", "YY", "h","hh", "mm"}, new String[]{"-", "dd", "yyyy", "yy", "H", "HH", "MM"});

    try {
      SimpleDateFormat format = new SimpleDateFormat(dateFormat);
      format.setLenient(false);
      format.parse(dateValue);
      return false;
    } catch (Exception e) {
      return true;
    }
  }

I need to check if a valid format is passed first, and then parse the dateValue.

How to&Answers: