Wanted to convert the following dates format:
Mar 10th 2016
Mar 1st 2016
Mar 2nd 2016
Mar 3rd 2016
Mar 22nd 2016
into
10-03-2016
01-03-2016
02-03-2016
03-03-2016
22-03-2016
Tried couple of things but failed to get the desired output.
Wanted to convert the following dates format:
Mar 10th 2016
Mar 1st 2016
Mar 2nd 2016
Mar 3rd 2016
Mar 22nd 2016
into
10-03-2016
01-03-2016
02-03-2016
03-03-2016
22-03-2016
Tried couple of things but failed to get the desired output.
Try string manipulation. Read the input, split based on space and write a logic for your own converter
As there is no pattern in SimpleDateFormat
for ordinal day numbers, you first should clean the string, then parse the date and stringify it back using two SimpleDateFormat
s:
static final DateFormat DF_FROM = new SimpleDateFormat("MMM d yyyy", Locale.ENGLISH);
static final DateFormat DF_TO = new SimpleDateFormat("dd-MM-yyyy");
synchronized static String convert(String date) throws ParseException {
date = date.replaceAll("(?<=\\d)(st|nd|rd|th)", ""); // remove ordinal suffix
return DF_TO.format(DF_FROM.parse(date)); // convert
}
Please note usage of synchronized
for method as SimpleDateFormat
methods are not thread-safe.
Try this :)
private String converter (String in) throws Exception {
String stringMonth = in.split(" ")[0];
Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(stringMonth);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = Integer.valueOf(in.split(" ")[1].replaceAll("[a-z]", ""));
int year = Integer.valueOf(in.split(" ")[2]) - 1900;
Date result = new Date();
result.setYear(year);
result.setMonth(month);
result.setDate(day);
DateTime dt = new DateTime(result);
return dt.toString("dd-MM-yyyy");
}