我想用H:MM:SS这样的模式以秒为单位格式化持续时间。java中当前的实用程序设计用于格式化时间,而不是持续时间。
当前回答
如果你不想拖进库,使用Formatter或相关的快捷方式就足够简单了。给定整数秒数s:
String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
其他回答
在scala中,不需要库:
def prettyDuration(str:List[String],seconds:Long):List[String]={
seconds match {
case t if t < 60 => str:::List(s"${t} seconds")
case t if (t >= 60 && t< 3600 ) => List(s"${t / 60} minutes"):::prettyDuration(str, t%60)
case t if (t >= 3600 && t< 3600*24 ) => List(s"${t / 3600} hours"):::prettyDuration(str, t%3600)
case t if (t>= 3600*24 ) => List(s"${t / (3600*24)} days"):::prettyDuration(str, t%(3600*24))
}
}
val dur = prettyDuration(List.empty[String], 12345).mkString("")
下面是在Kotlin中将java.time.Duration转换为一个漂亮的字符串的一行代码:
duration.run {
"%d:%02d:%02d.%03d".format(toHours(), toMinutesPart(), toSecondsPart(), toMillisPart())
}
示例输出: 120:56:03.004
我使用Apache common的DurationFormatUtils,就像这样:
DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);
我的库Time4J提供了一个基于模式的解决方案(类似于Apache DurationFormatUtils,但更灵活):
Duration<ClockUnit> duration =
Duration.of(-573421, ClockUnit.SECONDS) // input in seconds only
.with(Duration.STD_CLOCK_PERIOD); // performs normalization to h:mm:ss-structure
String fs = Duration.formatter(ClockUnit.class, "+##h:mm:ss").format(duration);
System.out.println(fs); // output => -159:17:01
这段代码演示了处理小时溢出和符号处理的功能,请参见基于模式的持续时间格式化程序的API。
查看所有这些计算,大多数单位(小时、分钟等)都有一个. tofoopart()方便方法,这可能是有帮助的。
E.g.
Duration.ofMinutes(110L).toMinutesPart() == 50
读:到父单位(小时)的下一个值的分钟数。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap