3

この質問がいくつかの場所で尋ねられているのを見ましたが、与えられた答えは私には明確ではありません。それが私がそれをもう一度尋ねる理由です。

Locale引数を同じ日付パターンで渡すだけで、Locale固有の日付を取得することは可能ですか? たとえば、どうすればこのようなことができますか

String pattern = "dd/MM/yyyy";
Date d1 = new Date();
 SimpleDateFormat f1 =  new SimpleDateFormat( pattern , Locale.UK );
 f1.format(d1);
 // formatted date should be in  "dd/MM/yyyy" format

 SimpleDateFormat f2 =  new SimpleDateFormat( pattern , Locale.US );
 f2.format(d1);
 // formatted date should be in "MM/dd/yyyy" format

上記のコードでは、期待される結果が得られません。このようなことをする方法はありますか?

DateFormat ファクトリ メソッドを使用してみました。それに関する問題は、フォーマットパターンを渡すことができないことです。いくつかの定義済みの日付形式があります (SHORT、MEDIUM など)

前もって感謝します...

4

2 に答える 2

4

あなたはこのようなことを試すことができます

@Test
public void formatDate() {
    Date today = new Date();
    SimpleDateFormat fourDigitsYearOnlyFormat = new SimpleDateFormat("yyyy");
    FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);

    DateFormat dateInstanceUK = DateFormat.getDateInstance(DateFormat.SHORT, 
            Locale.UK);
    StringBuffer sbUK = new StringBuffer();

    dateInstanceUK.format(today, sbUK, yearPosition);

    sbUK.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), 
            fourDigitsYearOnlyFormat.format(today));
    System.out.println(sbUK.toString());

    DateFormat dateInstanceUS = DateFormat.getDateInstance(DateFormat.SHORT,
            Locale.US);
    StringBuffer sbUS = new StringBuffer();
    dateInstanceUS.format(today, sbUS, yearPosition);
    sbUS.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), 
            fourDigitsYearOnlyFormat.format(today));
    System.out.println(sbUS.toString());
}

基本的に、スタイルDateFormat#SHORTを使用して日付をフォーマットし、 FieldPositionオブジェクトを使用して年の位置をキャッチします。その後、年を 4 桁の形式に置き換えます。

出力は次のとおりです。

13/11/2013
11/13/2013

編集

あらゆるパターンで使用

StringBuffer sb = new StringBuffer();
DateFormat dateInstance = new SimpleDateFormat("yy-MM-dd");
System.out.println(dateInstance.format(today));
dateInstance.format(today, sb, yearPosition);
sb.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), 
        fourDigitsYearOnlyFormat.format(today));
System.out.println(sb.toString());

出力は次のとおりです。

13-11-13
2013-11-13
于 2013-11-13T09:24:12.050 に答える
0

これを使ってみてください:

DateFormat.getDateInstance(int style, Locale locale)

SimpleDataFormat の Java ドキュメントには、次のように記載されています。

指定されたパターンと指定されたロケールのデフォルトの日付形式記号を使用してSimpleDateFormatを構築します。注: このコンストラクターは、すべてのロケールをサポートしているわけではありません。完全にカバーするには、DateFormat クラスのファクトリ メソッドを使用します。

于 2013-11-13T08:46:09.317 に答える