Reputation: 7268
I'm trying to get a jodatime
DateTime
object to output in the format that I want. At the moment, my format string is:
dt.toString("EEEE dd\nMMMM YYYY");
This outputs as:
Wednesday 04
June 2014
However I'd like to display the DAY
with the suffix, for example:
1st
, 2nd
, 3rd
, 4th
Is there a built-in way of doing this with jodatime, or do I have to write my own function for this?
Upvotes: 2
Views: 3000
Reputation: 561
Here is a similar Kotlin version of this answer. This just outputs Months including their Ordinal.
fun getDayOfMonthDayWithOrdinal(date: DateTime): String {
val formatter = DateTimeFormat.forPattern("dd")
val monthDay = formatter.print(date).toInt()
return when (monthDay) {
1, 21, 31 -> "${monthDay}st"
2, 22 -> "${monthDay}nd"
3, 23 -> "${monthDay}rd"
else -> "${monthDay}th"
}
}
Upvotes: 2
Reputation: 44071
DateTime dt = new DateTime();
String formatFirst = "EEEE dd'st'\nMMMM YYYY";
String formatSecond = "EEEE dd'nd'\nMMMM YYYY";
String formatThird = "EEEE dd'rd'\nMMMM YYYY";
String formatStd = "EEEE dd'th'\nMMMM YYYY";
String pattern;
switch (dt.getDayOfMonth()) {
case 1:
case 21:
case 31:
pattern = formatFirst;
break;
case 2:
case 22:
pattern = formatSecond;
break;
case 3:
case 23:
pattern = formatThird;
break;
default:
pattern = formatStd;
}
String output = dt.toString(pattern, Locale.ENGLISH);
System.out.println(output);
Upvotes: 2
Reputation: 429
Judging by the docs on the JodaTime website (http://www.joda.org/joda-time/key_format.html), it doesn't look like there is a built in function to do this format.
Can see a similar question here as well for an example of how to manually do the formatting -- How do you format the day of the month to say "11th", "21st" or "23rd" in Java? (ordinal indicator)
Upvotes: 2
Reputation: 47300
You'll jave to implement your own DateTimeFormatterBuilder for that.
Upvotes: 0