0

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.

svichkar
  • 1,806
  • 1
  • 17
  • 23
user2459816
  • 85
  • 2
  • 11

3 Answers3

0

Try string manipulation. Read the input, split based on space and write a logic for your own converter

RadAl
  • 404
  • 5
  • 23
0

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 SimpleDateFormats:

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.

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
0

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");
}
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
svichkar
  • 1,806
  • 1
  • 17
  • 23