如何在 Java 中将毫秒转换为“X 分钟,x 秒”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/625433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Milliseconds to "X mins, x seconds" in Java?
提问by Click Upvote
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.
我想记录System.currentTimeMillis()
用户在我的程序中开始某事时使用的时间。当他完成后,我会减去当前System.currentTimeMillis()
从start
变量,我想向他们展示使用人类可读的格式经过诸如“XX小时XX分钟,XX秒”,甚至是“XX分钟,XX秒”的时间,因为它的不太可能花一个小时的时间。
What's the best way to do this?
做到这一点的最佳方法是什么?
采纳答案by siddhadev
Use the java.util.concurrent.TimeUnit
class:
使用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))
);
Note: TimeUnit
is part of the Java 1.5 specification, but toMinutes
was added as of Java 1.6.
注意:TimeUnit
是 Java 1.5 规范的一部分,但从toMinutes
Java 1.6 开始添加。
To add a leading zero for values 0-9, just do:
要为值 0-9 添加前导零,只需执行以下操作:
String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
If TimeUnit
or toMinutes
are unsupported (such as on Android before API version 9), use the following equations:
如果TimeUnit
或toMinutes
不受支持(例如在 API 版本 9 之前的 Android 上),请使用以下等式:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
//etc...
回答by Bombe
Uhm... how many milliseconds are in a second? And in a minute? Division is not that hard.
嗯……一秒是多少毫秒?一分钟后?分工没那么难。
int seconds = (int) ((milliseconds / 1000) % 60);
int minutes = (int) ((milliseconds / 1000) / 60);
Continue like that for hours, days, weeks, months, year, decades, whatever.
继续这样持续数小时、数天、数周、数月、一年、数十年等等。
回答by cadrian
Either hand divisions, or use the SimpleDateFormat API.
要么手动分割,要么使用SimpleDateFormat API。
long start = System.currentTimeMillis();
// do your work...
long elapsed = System.currentTimeMillis() - start;
DateFormat df = new SimpleDateFormat("HH 'hours', mm 'mins,' ss 'seconds'");
df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
System.out.println(df.format(new Date(elapsed)));
Edit by Bombe: It has been shown in the comments that this approach only works for smaller durations (i.e. less than a day).
Bombe编辑:评论中显示这种方法仅适用于较短的持续时间(即不到一天)。
回答by Thilo
I would not pull in the extra dependency just for that (division is not that hard, after all), but if you are using Commons Lang anyway, there are the DurationFormatUtils.
我不会为此引入额外的依赖项(毕竟,除法并不难),但是如果您无论如何都在使用 Commons Lang,则有DurationFormatUtils。
Example Usage (adapted from here):
示例用法(改编自此处):
import org.apache.commons.lang3.time.DurationFormatUtils
public String getAge(long value) {
long currentTime = System.currentTimeMillis();
long age = currentTime - value;
String ageString = DurationFormatUtils.formatDuration(age, "d") + "d";
if ("0d".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "H") + "h";
if ("0h".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "m") + "m";
if ("0m".equals(ageString)) {
ageString = DurationFormatUtils.formatDuration(age, "s") + "s";
if ("0s".equals(ageString)) {
ageString = age + "ms";
}
}
}
}
return ageString;
}
Example:
例子:
long lastTime = System.currentTimeMillis() - 2000;
System.out.println("Elapsed time: " + getAge(lastTime));
//Output: 2s
Note: To get millis from two LocalDateTime objects you can use:
注意:要从两个 LocalDateTime 对象中获取毫秒,您可以使用:
long age = ChronoUnit.MILLIS.between(initTime, LocalDateTime.now())
回答by Xtera
I think the best way is:
我认为最好的方法是:
String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toSeconds(length)/60,
TimeUnit.MILLISECONDS.toSeconds(length) % 60 );
回答by user85421
For small times, less than an hour, I prefer:
对于小时间,不到一个小时,我更喜欢:
long millis = ...
System.out.printf("%1$TM:%1$TS", millis);
// or
String str = String.format("%1$TM:%1$TS", millis);
for longer intervalls:
对于更长的间隔:
private static final long HOUR = TimeUnit.HOURS.toMillis(1);
...
if (millis < HOUR) {
System.out.printf("%1$TM:%1$TS%n", millis);
} else {
System.out.printf("%d:%2$TM:%2$TS%n", millis / HOUR, millis % HOUR);
}
回答by fredcrs
Just to add more info if you want to format like: HH:mm:ss
如果您想使用以下格式添加更多信息:HH:mm:ss
0 <= HH <= infinite
0 <= HH <= 无限
0 <= mm < 60
0 <= 毫米 < 60
0 <= ss < 60
0 <= ss < 60
use this:
用这个:
int h = (int) ((startTimeInMillis / 1000) / 3600);
int m = (int) (((startTimeInMillis / 1000) / 60) % 60);
int s = (int) ((startTimeInMillis / 1000) % 60);
I just had this issue now and figured this out
我现在刚刚遇到这个问题并想通了
回答by Brent Writes Code
Based on @siddhadev's answer, I wrote a function which converts milliseconds to a formatted string:
根据@siddhadev 的回答,我编写了一个将毫秒转换为格式化字符串的函数:
/**
* Convert a millisecond duration to a string format
*
* @param millis A duration to convert to a string form
* @return A string of the form "X Days Y Hours Z Minutes A Seconds".
*/
public static String getDurationBreakdown(long millis) {
if(millis < 0) {
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes ");
sb.append(seconds);
sb.append(" Seconds");
return(sb.toString());
}
回答by John
for correct strings ("1hour, 3sec", "3 min" but not "0 hour, 0 min, 3 sec") i write this code:
对于正确的字符串(“1 小时,3 秒”,“3 分钟”但不是“0 小时,0 分钟,3 秒”),我写了这个代码:
int seconds = (int)(millis / 1000) % 60 ;
int minutes = (int)((millis / (1000*60)) % 60);
int hours = (int)((millis / (1000*60*60)) % 24);
int days = (int)((millis / (1000*60*60*24)) % 365);
int years = (int)(millis / 1000*60*60*24*365);
ArrayList<String> timeArray = new ArrayList<String>();
if(years > 0)
timeArray.add(String.valueOf(years) + "y");
if(days > 0)
timeArray.add(String.valueOf(days) + "d");
if(hours>0)
timeArray.add(String.valueOf(hours) + "h");
if(minutes>0)
timeArray.add(String.valueOf(minutes) + "min");
if(seconds>0)
timeArray.add(String.valueOf(seconds) + "sec");
String time = "";
for (int i = 0; i < timeArray.size(); i++)
{
time = time + timeArray.get(i);
if (i != timeArray.size() - 1)
time = time + ", ";
}
if (time == "")
time = "0 sec";
回答by Damien
long time = 1536259;
return (new SimpleDateFormat("mm:ss:SSS")).format(new Date(time));
Prints:
印刷:
25:36:259
25:36:259