我知道您可以使用 DateUtils.formatElapsedTime(seconds) 将秒数转换为 HH:MM 格式的 String:SS.但是是否有任何实用函数可以让我执行相同的转换但没有秒?
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?
例如,我想将 3665 秒转换为 1:01,即使它正好是 1:01:05.换句话说,只需删除秒部分.
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.
推荐答案根据可用信息,您似乎想要格式化基于持续时间的值.幸运的是,从 Java 8 开始,现在有一个新的 java.time API,其中包含一个 Duration 类.
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)));打印出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 ;)
更多推荐
在 Java 中将秒数转换为 HH:MM(不含秒)
发布评论