many times I've tried to figure out how to parse different date formats. On the input we have some lines:
1987-03-23
null
1985-11-29
23-07-2000
17-10-1984
It should be translated into the Russian(As in my task, you can change it) format dd.MM.yyyy and where it does not match the pattern to draw a dash.
I decided so:
public class DateUtil {
public static String validDateString(String strDate) {
final List<String> dateFormats = Arrays.asList("yyyy-MM-dd", "dd-MM-yyyy", "MM-dd-
yyyy", "MM/dd/yyyy", "dd/MM/yyyy");
SimpleDateFormat sdf;
//Our new format
final String RU_FORMAT = "dd.MM.yyyy";
String output = "-";
//Reviewing for all templates
for (String format : dateFormats) {
sdf = new SimpleDateFormat(format, new Locale("ru"));
//Do not try to analyze dates that do not match the format
sdf.setLenient(false);
try {
if (sdf.parse(strDate) != null) {
Date date = sdf.parse(strDate);
sdf.applyPattern(RU_FORMAT);
return sdf.format(date);
}
break;
} catch (ParseException e) {
}
}
//Display line with a dash
return output;
}
}
Call this method you can by this line:
DateUtil.validDateString(input_line);