Search code examples
javadate-format

define the date format java 'rd' 'st' 'th' 'nd'


I have a String "Saturday, Oct, 25th, 11:40"

What format does this date has? How can I parse the ordinal indicator?

Here is how i want to convert it

private String changeDateFormat(String stringDate){

        DateFormat dateFormat = new SimpleDateFormat("DD, MM, ddth, hh:mm");
        try {
            Date date = dateFormat.parse(stringDate);
            dateFormat = new SimpleDateFormat("ddMMMyyyy");
            stringDate=dateFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return stringDate.toUpperCase();
    }

Solution

  • SimpleDateFormat doesn't seem to easily handle day numbers followed by "st" "th" etc. A simple solution would be remove that part of the original string. E.g.

    int comma = original.lastIndexOf(',');
    String stringDate =
            original.substring(0, comma - 2) +
            original.substring(comma + 1);
    

    After that just use this format on stringDate:

    SimpleDateFormat("EE, MM, dd, hh:mm")