Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format date to string like "31st Dec, 2000" in Java [duplicate]

I tried to use the SimpleDateFormat class to do this, But I did not find any options that put a 'st' after the day. I could only get '31 Dec, 2000'

How to format like "31st Dec, 2000" . I have the date in milliseconds.

Is there any API in java that lets us format a date this way?

like image 725
Ronnie Avatar asked Nov 30 '22 14:11

Ronnie


2 Answers

A simple function with switch case, do this

Public String getDateSuffix( int day) { 
        switch (day) {
            case 1: case 21: case 31:
                   return ("st");

            case 2: case 22: 
                   return ("nd");

            case 3: case 23:
                   return ("rd");

            default:
                   return ("th");
        }
}
like image 143
Vinesh Avatar answered Dec 04 '22 11:12

Vinesh


The small function below will return a String suffix. (Stolen from this answer).

String getDayOfMonthSuffix(final int n) {
    if (n < 1 || n > 31) {
        throw new IllegalArgumentException("Illegal day of month");
    }

    if (n >= 11 && n <= 13) {
        return "th";
    }

    switch (n % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
}

Then, all you need to do is something like:

SimpleDateFormat dd = new SimpleDateFormat("dd");
SimpleDateFormat mmyyyy = new SimpleDateFormat("MMM, yyyy");

String formattedDate = dd.format(date) + getDayOfMonthSuffix(date.get(Calendar.DAY_OF_MONTH)) + " " + mmyyyy.format(date);
like image 26
Redandwhite Avatar answered Dec 04 '22 11:12

Redandwhite