あなたがそうする必要はないと思います。日付へのこの種の追加については、明確に定義された規則があります。
- 日付が 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