これを行うためにクラスを使用しようとしましたが、日の後に「st」SimpleDateFormat
を置くオプションが見つかりませんでした。「2000 年 12 月 31 日」しか取得できませんでした
「2000 年 12 月 31 日」のようにフォーマットする方法。私はミリ秒単位で日付を持っています。
この方法で日付をフォーマットできるJavaのAPIはありますか?
これを行うためにクラスを使用しようとしましたが、日の後に「st」SimpleDateFormat
を置くオプションが見つかりませんでした。「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");
}
}
コメントで返信しましたが、コードを削除できると思いました。
/**
* 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];
}
以下の小さな関数は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);
値の配列を使用できます。
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];
}