0

what will be the date format of dates like :
1st April,2016
3rd April,2016
22nd April,2016

And is there any API to parse dates like that ?

Edit : Dupllicate questions does not contain any answer about parsing date containg 1(st), 2(nd),3(rd).I don't know how to parse st in 1st, nd in 2nd and rd in 3rd.

andy
  • 37
  • 1
  • 7

1 Answers1

1

The problem is that Java doesn't understand the ordinal indicator suffix, 1st, 2nd 3rd etc. You firstly need to remove this and then pass that into a DateFormat.

I'd also recommend ensuring your Locale is set correctly, as "April" will be a different string in different languages which will effect geographical portability of your software.

public static void main(String[] args) throws ParseException {
    System.out.println(parseWithOrdinals("1st April,2016"));
    System.out.println(parseWithOrdinals("3rd April,2016"));
    System.out.println(parseWithOrdinals("22nd April,2016"));
}

private static Date parseWithOrdinals(String date) throws ParseException {
    DateFormat format = new SimpleDateFormat("dd MMM,yyyy", Locale.UK);
    String corrected = date.replaceFirst("(\\d+)+.*\\s(.*)", "$1 $2");
    return format.parse(corrected);
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Adam
  • 35,919
  • 9
  • 100
  • 137