How to display time amount to user?

我怕爱的太早我们不能终老 提交于 2021-02-17 04:45:44

问题


I want to convert time amount from milli-sec to a human readable string.

For example:

3,600,000 should be displayed as 1:00:00 (1 hour).

Is there an existing library or class in Java that can do that?


回答1:


Since 1.5 there is the java.util.concurrent.TimeUnit class, use it like this:

String.format("%d min, %d sec", 
    TimeUnit.MILLISECONDS.toMinutes(millis),
    TimeUnit.MILLISECONDS.toSeconds(millis) - 
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);

For Versions below 1.5 You have to use

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);


来源:https://stackoverflow.com/questions/7862994/how-to-display-time-amount-to-user

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!