4

これを行うためにクラスを使用しようとしましたが、日の後に「st」SimpleDateFormatを置くオプションが見つかりませんでした。「2000 年 12 月 31 日」しか取得できませんでした

「2000 年 12 月 31 日」のようにフォーマットする方法。私はミリ秒単位で日付を持っています。

この方法で日付をフォーマットできるJavaのAPIはありますか?

4

5 に答える 5

14

スイッチケース付きのシンプルな機能、これを行う

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");
        }
}
于 2012-09-10T12:01:27.940 に答える
2

コメントで返信しましたが、コードを削除できると思いました。

/**
 * 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));
于 2012-09-10T11:51:44.793 に答える
2

これは少し短いかもしれません:

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];
}
于 2012-09-10T11:55:32.487 に答える
2

以下の小さな関数は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);
于 2012-09-10T11:49:58.633 に答える
1

値の配列を使用できます。

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];
}
于 2012-09-10T11:56:38.103 に答える