你如何格式化一个月中的一天来说“11th",“21st"?或“23日"(序数指标)? [英] How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

查看:39
本文介绍了你如何格式化一个月中的一天来说“11th",“21st"?或“23日"(序数指标)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这会给我一个月中的日期作为数字(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).

这篇关于你如何格式化一个月中的一天来说“11th",“21st"?或“23日"(序数指标)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆