Java Date または Timestamp を次のようなものに変換できる Java クラスまたはサンプル コードはありますか。
"3 hours"
" 20 seconds"
"25 minutes"
ファイルを生成するのにどれだけの時間がかかったかを示すために、Web アプリケーションでこれらの文字列が必要です (もちろん、かなり印刷された方法で:))
ありがとう、
Java Date または Timestamp を次のようなものに変換できる Java クラスまたはサンプル コードはありますか。
"3 hours"
" 20 seconds"
"25 minutes"
ファイルを生成するのにどれだけの時間がかかったかを示すために、Web アプリケーションでこれらの文字列が必要です (もちろん、かなり印刷された方法で:))
ありがとう、
JodaTime を使用:
PeriodFormat.getDefault( ).print( Hours.THREE );
PeriodFormat.getDefault( ).print( Seconds.seconds( 25 ) );
PeriodFormat.getDefault( ).print( Minutes.minutes( 20 ) );
PSまた、2つの時点の間の時間/秒/分の数を取得するのは非常に簡単です。
全体的には 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();
}
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
もちろん、これを拡張して、日/月/年などを含めることができます。
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);
...
SimpleDateFormat を使用してみてください: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
これはTimeAgoとよく似ています。そこにあるコードを活用して、このような期間をフォーマットできる場合があります。