有没有Java类或一些示例代码,可以将Java Date或Timestamp转换成类似于以下内容的东西:
"3 hours"
" 20 seconds"
"25 minutes"
我需要在我的Web应用程序中使用这些字符串,以展示生成文件所需的时间(当然要以漂亮的方式呈现 :))
谢谢,
"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 ) );
另外,在两个时间点之间获取小时数/秒数/分钟数也非常容易。
使用JodaTime是最好的方法,但以下是一种不使用任何领域特定库的方法,间接地在MessageFormat
的上下文中使用ChoiceFormat
:
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);
...
TimeZone
,这是可行的:http://stackoverflow.com/questions/2705674 - trashgod