-2

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?

Community
  • 1
  • 1
ATMTA
  • 767
  • 6
  • 18
  • What are you using to input the dates ? And for the where should it happen part , the code/overall structure on which you are working would be required. – Rndm Jul 29 '12 at 11:21

1 Answers1

1

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"));
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436