2

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?

Mike Baxter
  • 6,868
  • 17
  • 67
  • 115
  • I apologize for the duplicate question. http://stackoverflow.com/questions/4011075/how-do-you-format-the-day-of-the-month-to-say-11th-21st-or-23rd-in-java?lq=1 – Mike Baxter Jun 04 '14 at 14:51
  • 1
    its not _exactly_ a duplicate... you are asking specifically jodatime, looks like that one is more generically java. :) – BlakeP Jun 04 '14 at 15:04

4 Answers4

2

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)

Community
  • 1
  • 1
BlakeP
  • 429
  • 4
  • 8
2
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);
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
2

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"
        }
    }
badvok
  • 421
  • 3
  • 11
0

You'll jave to implement your own DateTimeFormatterBuilder for that.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311