5

Java Date または Timestamp を次のようなものに変換できる Java クラスまたはサンプル コードはありますか。

"3 hours"
" 20 seconds"
 "25 minutes"

ファイルを生成するのにどれだけの時間がかかったかを示すために、Web アプリケーションでこれらの文字列が必要です (もちろん、かなり印刷された方法で:))

ありがとう、

4

5 に答える 5

8

JodaTime を使用:

PeriodFormat.getDefault( ).print( Hours.THREE );
PeriodFormat.getDefault( ).print( Seconds.seconds( 25 ) );
PeriodFormat.getDefault( ).print( Minutes.minutes( 20 ) );

PSまた、2つの時点の間の時間/秒/分の数を取得するのは非常に簡単です。

于 2010-08-27T21:30:46.013 に答える
3

全体的には JodaTime を使用するのが最善の方法ですが、ドメイン固有のライブラリを使用せずChoiceFormatに a のコンテキストで間接的にを使用する 1 つの方法を次に示しますMessageFormat

static String choiceFor(int index, String noun) {
    return "{index,choice,0#|1#1 noun |1<{index,number,integer} nouns }"
        .replace("index", String.valueOf(index))
        .replace("noun", noun);
}
static String prettyPrint(int h, int m, int s) {
    String fmt = 
        choiceFor(0, "hour") +
        choiceFor(1, "minute") +
        choiceFor(2, "second");
    return java.text.MessageFormat.format(fmt, h, m, s).trim();
}

( ideone.com で見られるように):

    System.out.println(prettyPrint(1,2,3));
    // 1 hour 2 minutes 3 seconds

    System.out.println(prettyPrint(0,0,7));
    // 7 seconds

    System.out.println(prettyPrint(1,0,1));
    // 1 hour 1 second

    System.out.println(prettyPrint(0,2,0));
    // 2 minutes

もちろん、これを拡張して、日/月/年などを含めることができます。

于 2010-08-28T04:33:25.490 に答える
2

Javaクラスから時、分、秒を取得し、Calendarそれらを好きなものと連結できます(時間、分...)

Calendar c = Calendar.getInstance();
c.setTimeinMillis(<the time in milli second format (a long number)>);

int hours = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MIN);
...
于 2010-08-27T21:28:33.377 に答える
1

SimpleDateFormat を使用してみてください: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

于 2010-08-27T21:39:59.650 に答える
1

これはTimeAgoとよく似ています。そこにあるコードを活用して、このような期間をフォーマットできる場合があります。

于 2010-08-27T21:27:58.513 に答える