Search code examples
javastruts-1

input date in two different formats. How to parse it


Possible Duplicate:
How to parse dates in multiple formats using SimpleDateFormat

I'm using a to get input date. The date string can be in two different formats - MM/dd/yyy and dd.MM.yyyy. After submitting I need to parse this string into sql.Date and set it as a property of the nested object in ActionForm. What is the best way to parse this string in different formats and where should it happen?


Solution

  • First check whether the string contains a "." or a "/" and then apply the appropriate DateFormat.

    static Date parseDate(String in) throws ParseException {
      return new SimpleDateFormat(in.contains(".")? "dd.MM.yyyy" : "MM/dd/yyyy")
        .parse(in);
    }
    public static void main(String[] args) throws Exception {
      System.out.println(parseDate("31.01.2001"));
      System.out.println(parseDate("01/31/2001"));
    }