I implemented the following method that can be used to convert a String to an accepted format:
public static Date parseDate(final String dateString, final String[] acceptedFormats) {
for (String format : acceptedFormats) {
try {
return new SimpleDateFormat(format).parse(dateString);
} catch (ParseException e) {
// dateString does not have this format
}
}
return null; // dateString does not match any accepted format
}
As I read from some Java books, its not a good practice to use exceptions to control the flow. In this case, I use an empty catch block and that
s not a good practice. Can you help me to to write a method that does the same thing but in a different way?
I have to mention that I am not allowed to use external libs( I know that there a lib from apachee that can do this thing in a nice manner)
You can use the overload of parse
which takes a ParsePosition
:
public static Date parseDate(final String dateString, final String[] acceptedFormats) {
ParsePosition position = new ParsePosition(0);
for (String format : acceptedFormats) {
// TODO: Specify time zone and locale
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = format.parse(text, position);
if (date != null && position.getIndex() == text.length()) {
return date;
}
position.setIndex(0);
}
return null; // dateString does not match any accepted format
}
Note the check that the parse position is the length of the string - that prevents false positives where some of the text has been parsed, but there's more left over - such as a format of "yyyy-MM-dd" and text of "2015-07-02T15:40".
See more on this question at Stackoverflow