[英]Java pretty print for duration
Is there Java class or some sample code that can convert a java Date or Timestamp into something like: 是否有Java类或一些示例代码可以将java Date或Timestamp转换为:
"3 hours"
" 20 seconds"
"25 minutes"
I need those strings in my web application to show how much it took to generate a file (in a pretty print way of course :) ) 我需要在我的Web应用程序中使用这些字符串来显示生成文件所需的时间(当然是以漂亮的打印方式:))
Thanks, 谢谢,
PeriodFormat.getDefault( ).print( Hours.THREE );
PeriodFormat.getDefault( ).print( Seconds.seconds( 25 ) );
PeriodFormat.getDefault( ).print( Minutes.minutes( 20 ) );
PS Also it's very easy to get the number of hours/seconds/minutes between 2 time points. PS此外,很容易获得2个时间点之间的小时/秒/分钟数。
Using JodaTime is the best overall approach, but here's one way to do it without using any domain-specific libraries, using the ChoiceFormat
indirectly in the context of a MessageFormat
: 使用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();
}
Now you can have ( as seen on ideone.com ): 现在你可以拥有( 如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
You can of course extend this to include days/months/years/etc. 您当然可以将其扩展到包括天/月/年/等。
you can get the hours, minutes and seconds from java Calendar
class and then concat them with what ever you like (hours , mins ...) 你可以从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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.