java - Avoiding a particular check for YYYY-MM--dd format in date -


i have below method in different date patterns have been handled

below method in different date formats have been handled

now particulat format yyyy-mm-dd don't want go check prefixing 20 before in code please advise how can skip part lets if date pattern yyyy-mm-dd avoid logic of prefixing 20 in front of year

below code

public java.util.date extractdate(string datestr, string datetype) {          string[] datepatternsofuk = { "d-m-yy", "d-m-yyyy", "d/m/yy", "d/m/yyyy", "yyyy-mm-dd","dd-mm-yy", "dd-mmm-yy","dd-mmm-yyyy","dd-mm-yyyy",                 "dd/mm/yy","dd/mmm/yy","dd/mmm/yyyy"};         string[] datepatternsofus = { "m-d-yy","mm-dd-yy","m/d/yy","mm/dd/yy", "mm/dd/yy", "mmm-dd-yy",                 "mmm/dd/yy", "mmm-dd-yyyy", "mm-dd-yyyy", "mmm/dd/yyyy",                 "mm/dd/yyyy" };         java.util.date date = null;         string[] datepatterns = datepatternsofuk;          if (datetype.equals("us")) {              datepatterns = datepatternsofus;         } else if (datetype.equals("uk")) {              datepatterns = datepatternsofuk;         }           ///******code should not go in check date pattern yyyy-mm-dd          int p = datestr.lastindexof("/");         if (p == -1) {             p = datestr.lastindexof("-");         }         string firstsubstring = datestr.substring(0, p + 1);         string secondsubstring = datestr.substring(p + 1);         if (p != -1 && secondsubstring.length() <= 2) {             secondsubstring = integer.tostring(2000 + integer.parseint(secondsubstring));             datestr = firstsubstring + secondsubstring;         }           ///****************************************//          try {             date = dateutils.parsedate(datestr, datepatterns);          } catch (parseexception ex) {             logger.error("##$$$$$### error in invoice inside extractdate method : ##$$$$$$#### "                     + errorutility.getstacktraceforexception(ex));          }         return date;     } 

you avoid trying any inappropriate pattern checking if string "looks like" pattern before parsing pattern.

the general way is:

string datepattern = "yyyy-mm-dd"; // example string input;   if (input.matches(datepattern.replaceall("\\w", "\\d"))) {     // input looks pattern     // in example "dddd-dd-dd" "d" digit     // go ahead , try parse } 

you can enhance logic add:

if (input.matches("\\d\\d\\d.*")) {     // has 2 digit year, add "20" front } 

Comments