你如何格式化一个月中的一天来说“11th",“21st"?或“23日"(序数指标)?

2022-01-30 00:00:00 date ordinal simpledateformat java

我知道这会给我一个月中的日期作为数字(112123):

I know this will give me the day of the month as a number (11, 21, 23):

SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");

但是如何格式化一个月中的一天以包含 序数指标,说 11th21st 还是 23rd?

But how do you format the day of the month to include an ordinal indicator, say 11th, 21st or 23rd?

推荐答案

// 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 的表格很不错,但由于重复了相同的信息,它为错误打开了机会.在 7tn17tn27tn 的表中确实存在这样的错误(此错误可能会随着时间的推移而得到修复,因为流动性StackOverflow 的性质,因此请检查答案上的版本历史以查看错误).

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).

相关文章