如何将毫秒转换为“X 分钟,x 秒"?在爪哇? [英] How to convert Milliseconds to "X mins, x seconds" in Java?

查看:31
本文介绍了如何将毫秒转换为“X 分钟,x 秒"?在爪哇?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 System.currentTimeMillis() 记录用户在我的程序中开始某事时的时间.当他完成时,我将从 start 变量中减去当前的 System.currentTimeMillis(),并且我想使用人类可读的格式向他们显示经过的时间,例如"XX 小时,XX 分钟,XX 秒"甚至XX 分钟,XX 秒",因为它不太可能需要一个小时.

I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.

最好的方法是什么?

推荐答案

使用 java.util.concurrent.TimeUnit 类:

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

注意:TimeUnit 是 Java 1.5 规范的一部分,但 toMinutes 从 Java 1.6 开始添加.

Note: TimeUnit is part of the Java 1.5 specification, but toMinutes was added as of Java 1.6.

要为值 0-9 添加前导零,只需执行以下操作:

To add a leading zero for values 0-9, just do:

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

如果 TimeUnittoMinutes 不受支持(例如在 API 版本 9 之前的 Android 上),请使用以下等式:

If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations:

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

这篇关于如何将毫秒转换为“X 分钟,x 秒"?在爪哇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆