如何格式化一个月的日子,以说“第11”,“第21”或“第23”在Java中? (顺序指标) [英] How do you format the day of the month to say "11th", "21st" or "23rd" in Java? (ordinal indicator)

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

问题描述

我知道这会把这个月的日子作为一个数字( 11 21 23 ):

  SimpleDateFormat formatDayOfMonth = new SimpleDateFormat(d); 

但是,如何格式化一个月的日期,以包含 ordinal indicator ,说 11th 21st 23rd 在Java?

解决方案

  // http://code.google.com/p/guava-libraries 
import static com.google.common.base.Preconditions。*;

String getDayOfMonthSuffix(final int n){
checkArgument(n> = 1&& n< = 31,非法日期:+ n)
if(n> = 11&< n = 13){
returnth;
}
开关(n%10){
案例1:返回st;
case 2:returnnd;
case 3:returnrd;
default:returnth;
}
}

@kaliatech的表格很不错,相同的信息重复,它打开了一个bug的机会。这样一个bug实际上存在于 7tn 17tn 27tn (由于StackOverflow的流畅性,此错误可能会随着时间的推移而得到修正,因此请检查答案中的版本历史记录查看错误)。


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

SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");

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

解决方案

// http://code.google.com/p/guava-libraries
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";
    }
}

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

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

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