Reputation: 83
In my code, I've to convert a String value(Input) to java.sql.Date format
. The problem I am facing is , the input date format is undefined, and it could be in any format. For example , input string may be "Jan 10,2014"
or "01-10-2014"
or "2014/Jan/10"
. So now I need to convert this input value into java.sql.Date(DD/MMMM/YYYY)
. Is there any way to do this conversion?
Upvotes: 1
Views: 191
Reputation: 7804
Try using a List
of all the patterns mentioned above using SimpledateFormat.
Something like this:
SimpleDateFormat format1 = new SimpleDateFormat("MMM dd,yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MMM/dd");
// Note: be sure about the format, or else you may end up assigning incorrect values
List<DateFormat> list = new ArrayList<DateFormat>();
list.add(format1);
list.add(format2);
list.add(format3);
for (DateFormat format : list) {
try {
System.out.println(format.parse("Jan 10,2014"));
// Match found. Take action
} catch (ParseException exception) {
// Ignore. Try other pattern
}
}
Upvotes: 0
Reputation: 53829
That is not possible.
You cannot differentiate dd/MM/yyyy
and MM/dd/yyyy
.
You really need to know the format otherwise your program will probably not behave the way you want.
Upvotes: 4