Search code examples
regexdatetimesalesforceapexsalesforce-lightning

I want to create a method to check if the Date is in 'mm/dd/yyyy' format in apex


This is the snippet I want to be the structure like this:

public static boolean validateDateFormat(String date1) {
  if(date1.format('mm/dd/yyyy')) {
    return true;
  } else {
    return false;
  }
}

Solution

  • A simple way to do it is by using regex:

    public static boolean validateDateFormat(String date1){
        Pattern pattern = Pattern.compile('\\d{2}/\\d{2}/\\d{4}'); 
        Matcher matcher = pattern.matcher(date1);
        return matcher.matches();
    }
    

    Note that \d specifies digit and the number in {} after it specifies the quantity e.g. \d{2} specifies 2 digits.