我试图使用SimpleDateFormat
类来做到这一点,但我没有找到任何在一天之后放置“st”的选项。我只能得到 “2000 年 12 月 31 日”
如何格式化“2000 年 12 月 31 日”。我有以毫秒为单位的日期。
java中是否有任何API可以让我们以这种方式格式化日期?
我试图使用SimpleDateFormat
类来做到这一点,但我没有找到任何在一天之后放置“st”的选项。我只能得到 “2000 年 12 月 31 日”
如何格式化“2000 年 12 月 31 日”。我有以毫秒为单位的日期。
java中是否有任何API可以让我们以这种方式格式化日期?
一个带开关盒的简单功能,这样做
Public String getDateSuffix( int day) {
switch (day) {
case 1: case 21: case 31:
return ("st");
case 2: case 22:
return ("nd");
case 3: case 23:
return ("rd");
default:
return ("th");
}
}
下面的小函数将返回一个String
后缀。(从此答案中窃取)。
String getDayOfMonthSuffix(final int n) {
if (n < 1 || n > 31) {
throw new IllegalArgumentException("Illegal day of month");
}
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";
}
}
然后,您需要做的就是:
SimpleDateFormat dd = new SimpleDateFormat("dd");
SimpleDateFormat mmyyyy = new SimpleDateFormat("MMM, yyyy");
String formattedDate = dd.format(date) + getDayOfMonthSuffix(date.get(Calendar.DAY_OF_MONTH)) + " " + mmyyyy.format(date);
我在评论中回复了,但我想我可以放弃代码。
/**
* Returns the appropriate suffix from th, nd or rd
* @param cal
* @return
*/
public static String dateSuffix(final Calendar cal) {
final int date = cal.get(Calendar.DATE);
switch (date % 10) {
case 1:
if (date != 11) {
return "st";
}
break;
case 2:
if (date != 12) {
return "nd";
}
break;
case 3:
if (date != 13) {
return "rd";
}
break;
}
return "th";
}
用法:
SimpleDateFormat sdf = new SimpleDateFormat("d'%s' MMM, yyyy");
String myDate = String.format(sdf.format(date), Util.dateSuffix(date));
这可能有点短:
String getDayOfMonthSuffix(final int n) {
if (n < 1 || n > 31) {
throw new IllegalArgumentException("Illegal day of month");
}
final String[] SUFFIX = new String[] { "th", "st", "nd", "rd" };
return (n >= 11 && n <= 13) || (n % 10 > 3) ? SUFFIX[0] : SUFFIX[n % 10];
}
您可以使用一组值。
private static final String[] TH_SUFFIX = ",st,nd,rd,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,st,nd,rd,th,th,th,th,th,th,th,st".split(",");
public static String getDayOfMonthSuffix(int n) {
return TH_SUFFIX[n];
}