我不认为你需要这样做。关于日期的这种附属物有明确定义的规则。
- 如果日期以 1 结尾且小于 10 或大于 20,则以 'st' 结尾。
- 如果日期以 2 结尾且小于 10 或大于 20,则以 'nd' 结尾。
- 如果日期以 3 结尾且小于 10 或大于 20,则以 'rd' 结尾。
- 所有其他日期以“th”结尾。
这是我设计过度的解决方案。从它那里得到你想要的。
public String appendDateEnding(String theDate) {
if(null != theDate) {
try {
return appendDateEnding(Integer.parseInt(theDate));
} catch (NumberFormatException e) {
// we'll return null since we don't have a valid date.
}
}
return null;
}
private String appendDateEnding(int theDate) {
StringBuffer result = new StringBuffer();
if(32 <= theDate || 0 >= theDate) {
throw new IllegalArgumentException("Invalid date.");
} else {
result.append(theDate);
int end = theDate % 10;
if(1 == end && isValidForSuffix(theDate)) {
result.append("st");
} else if(2 == end && isValidForSuffix(theDate)) {
result.append("nd");
} else if(3 == end && isValidForSuffix(theDate)) {
result.append("rd");
} else {
result.append("th");
}
}
return result.toString();
}
private boolean isValidForSuffix(int theDate) {
return (10 > theDate || 20 < theDate);
}
如果给定 1 到 31 之间的天数,它会打印什么:
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