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?
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");
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With