I know this will give me the day of the month as a number (11
, 21
, 23
):
SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");
But how do you format the day of the month to say 11th
, 21st
or 23rd
in Java?
I know this will give me the day of the month as a number (11
, 21
, 23
):
SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");
But how do you format the day of the month to say 11th
, 21st
or 23rd
in Java?
Because most countries don't use the format "October 24th, 2010," that functionality was never incorporated into most programming languages. There are workarounds, however. You can break up the two-digit day and use the last digit inside of a switch statement.
There is nothing in JDK to do this.
static string[] suffixes =
// 0 1 2 3 4 5 6 7 8 9
{ "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 10 11 12 13 14 15 16 17 18 19
"th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
// 20 21 22 23 24 25 26 27 28 29
"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 30 31
"th", "st" };
Date date = new Date();
SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");
int day = Integer.parseInt(formatDateOfMonth.format(date));
String dayStr = day + suffixes[day];
I didn't run this through a compiler, so might be errors, but you get the idea.
EDIT: I saw some quick down votes at first. Probably because of the perceived inefficiencies. Same thing, but less likely to offend:
Date date = new Date();
int day = Calendar.getInstance().setTime(date).get(Calendar.DAY_OF_MONTH);
String dayStr = day + suffixes[day];
String getSuffix(final int n) {
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";
}
}
The table from @kaliatech is nice, but since the same information is repeated, it opens the chance for a bug. Such a bug actually exists in the table for 7tn
, 17tn
, and 27tn
(this bug might get fixed as time goes on because of the fluid nature of StackOverflow, so check the version history on the answer to see the error).
String ordinal(int num)
{
string[] suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
int m = num % 100;
return String(num) + suffix[(m > 10 && m < 20) ? 0 : (m % 10)];
}