Convert number of seconds into HH:MM (without seconds) in Java

﹥>﹥吖頭↗ 提交于 2019-11-28 12:46:10

问题


I'm aware that you can use DateUtils.formatElapsedTime(seconds) to convert a number of seconds into a String with the format HH:MM:SS. But are there any utility functions that let me perform the same conversion but without the seconds?

For example, I want to convert 3665 seconds into 1:01, even though it's exactly 1:01:05. In other words, simply dropping the seconds part.

Would strongly prefer an answer that points to a utility function (if one exists) rather than a bunch of home rolled algorithms.


回答1:


Based on the available information, you seem to be wanting to format a duration based value. Lucky for us, since Java 8, there is now a new java.time API which includes a Duration class.

Unfortunately, it doesn't (at least the last time checked) support a formatter for it.

However, you could easily roll your own...

protected static String format(Duration duration) {
    long hours = duration.toHours();
    long mins = duration.minusHours(hours).toMinutes();
    return String.format("%02d:%02d", hours, mins);
}

Which when used with something like...

System.out.println(format(Duration.ofSeconds(3665)));

prints out 01:01.

Now I know you'd "prefer" utility methods, but you're unlikely to find something that fits your "every" need and this at least gives you a starting point. Besides, you could always make a pull request ;)




回答2:


MadProgrammer has already provided a good Java 8 answer (which will work in Java 6 and 7 too when you use the ThreeTen Backport). In Java 9 still a bit more of the calculation can be done in the library:

    int seconds = 3665;
    Duration dur = Duration.ofSeconds(seconds);
    String formatted = String.format("%d:%02d", dur.toHours(), dur.toMinutesPart());
    System.out.println(formatted);

Output:

1:01

The toMinutesPart method and other toXxxPart methods were introduced in Java 9.




回答3:


Use Apache Commons Lang

You could use utility class DateFormatUtils of Apache's well known utility library Commons Lang, combined with TimeUnit to convert from seconds to milliseconds:

static String format(long durationSeconds) {
    long durationMillis = TimeUnit.SECONDS.toMillis(durationSeconds);
    // Commons lang:
    return DurationFormatUtils.formatDuration(durationMillis, "HH:mm");
}

Use with input 3665 it prints:

01:01

Personally I'd prefer to use Java8 or Java9 standard library (see the other answers) rather than introducing a dependency just to make it 1 method call.



来源:https://stackoverflow.com/questions/50096083/convert-number-of-seconds-into-hhmm-without-seconds-in-java

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