如何设置月份中某一天的格式,使其显示为“11 日”、“21 日”或“23 日”(序号指示器)?

2022-08-31 06:46:34

我知道这将给我一个月的某一天作为数字(,,):112123

SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");

但是,如何设置月份中的某一天的格式以包含序号指示器,例如 ,或者?11th21st23rd


答案 1
// https://github.com/google/guava
import static com.google.common.base.Preconditions.*;

String getDayOfMonthSuffix(final int n) {
    checkArgument(n >= 1 && n <= 31, "illegal day of month: " + 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";
    }
}

@kaliatech的表格很好,但是由于重复了相同的信息,因此它为错误打开了机会。这样的 bug 实际上存在于 、 和 的表中(由于 StackOverflow 的流动性,随着时间的推移,此 bug 可能会得到修复,因此请检查答案上的版本历史记录以查看错误)。7tn17tn27tn


答案 2

JDK 中没有任何内容可以执行此操作。

  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];

或使用日历:

 Calendar c = Calendar.getInstance();
 c.setTime(date);
 int day = c.get(Calendar.DAY_OF_MONTH);
 String dayStr = day + suffixes[day];

根据@thorbj ørn-ravn-andersen的评论,这样的表在本地化时会很有帮助:

  static String[] suffixes =
     {  "0th",  "1st",  "2nd",  "3rd",  "4th",  "5th",  "6th",  "7th",  "8th",  "9th",
       "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th",
       "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th",
       "30th", "31st" };