Generic Date Parser in Java

I wrote this function because I was working on an application that stored a lot of dates as text, and they were a mixture of American (MM/dd/yyyy) and New Zealand formats (dd/MM/yyy).

Sometimes I knew what the format was, and other times I didn’t, so the method needed to be able to work it out as best it could.

The default format was assumed to be New Zealand (dd/MM/yyy).

/**
 * Converts a string to a date without needing to know the format.
 * Caution: Confusion between NZ and American may happen.
 * @param date
 * @param isAmerican: if the date is known to be American set to true
 * @return A correctly formatted date
 * @throws ParseException: thrown if the date format is not known
 */
public static Date parseDate(String date, Boolean isAmerican) throws ParseException{
       String pattern = "";
       if (date == null || date.trim().isEmpty())
              throw new ParseException("Date not supplied!");

       // make the separators a space
       String dateString = date.replace("/", " ").replace("-", " ");
       // find the format for the date
       if (regExFound("^\\d.*", dateString)) {
              // the first character is a digit
              if (regExFound("^\\d{2} \\d{2} \\d{4}.*", dateString)) {
                    if ((isAmerican && Integer.parseInt(dateString.substring(0, 2)) < 13)
                                  || Integer.parseInt(dateString.substring(3, 5)) > 12) {
                           // if the date is American and/or the month is within 12
                           pattern = "MM dd yyyy";
                    }
                    else
                           pattern = "dd MM yyyy";
              }
              else if (regExFound("^\\d{4} \\d{2} \\d{2}.*", dateString))
                    pattern = "yyyy MM dd";
              else if (regExFound("^\\d{2} \\w{3} \\d{4}.*", dateString))
                    pattern = "dd MMM yyyy";
              else if (regExFound("^\\d{2}.\\w*.\\d{4}.*", dateString))
                    pattern = "dd MMMM yyyy";
       }
       else
              throw new ParseException("Date Format not known.");
       
       // parse the date
       SimpleDateFormat sdf = new SimpleDateFormat(pattern);
       return sdf.parse(dateString);
}

private static Boolean regExFound(String pattern, String text) {
       Pattern p = Pattern.compile(pattern);
       Matcher m = p.matcher(text);
       return m.find();
}

Leave a Reply

Your email address will not be published. Required fields are marked *