Java 漂亮打印持续时间
是否有 Java 类或一些示例代码可以将 java 日期或时间戳转换为类似的内容:
"3 hours"
" 20 seconds"
"25 minutes"
我需要在我的 Web 应用程序中使用这些字符串来显示生成文件所需的时间(当然以漂亮的打印方式:))
谢谢,
Is there Java class or some sample code that can convert a java Date or Timestamp into something like:
"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 :) )
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 JodaTime 是最好的整体方法,但这是一种不使用任何特定于域的库的方法,使用
ChoiceFormat
间接在MessageFormat
:现在您可以拥有 (如 ideone.com 上所示):
您当然可以扩展此以包括天/月/年/等。
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 aMessageFormat
:Now you can have (as seen on ideone.com):
You can of course extend this to include days/months/years/etc.
您可以从 java
Calendar
类获取小时、分钟和秒,然后将它们与您喜欢的内容(小时、分钟...)连接起来you can get the hours, minutes and seconds from java
Calendar
class and then concat them with what ever you like (hours , mins ...)这听起来很像 TimeAgo。您也许可以利用其中的代码来格式化持续时间,如下所示。
This sounds very much like TimeAgo. You may be able to leverage the code in there to format durations like this.
尝试使用 SimpleDateFormat:
http://download.oracle.com/javase/ 6/docs/api/java/text/SimpleDateFormat.html
Try using SimpleDateFormat:
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
使用JodaTime:
PS也很容易获得2个时间点之间的小时/秒/分钟数。
With JodaTime:
P.S. Also it's very easy to get the number of hours/seconds/minutes between 2 time points.