有没有人知道Java库可以像C#一样以毫秒为单位漂亮地打印数字?
例如,123456毫秒的长度将打印为4d1h3m5s。
发布于 2010-08-13 03:44:28
使用PeriodFormatterBuilder,Joda Time有一个很好的方法来实现这一点。
速战速决:PeriodFormat.getDefault().print(duration.toPeriod());
例如:
//import org.joda.time.format.PeriodFormatter;
//import org.joda.time.format.PeriodFormatterBuilder;
//import org.joda.time.Duration;
Duration duration = new Duration(123456); // in milliseconds
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendDays()
.appendSuffix("d")
.appendHours()
.appendSuffix("h")
.appendMinutes()
.appendSuffix("m")
.appendSeconds()
.appendSuffix("s")
.toFormatter();
String formatted = formatter.print(duration.toPeriod());
System.out.println(formatted);
发布于 2016-11-08 20:54:42
我构建了一个简单的解决方案,使用Java8的Duration.toString()
和一些正则表达式:
public static String humanReadableFormat(Duration duration) {
return duration.toString()
.substring(2)
.replaceAll("(\\d[HMS])(?!$)", "$1 ")
.toLowerCase();
}
结果将如下所示:
- 5h
- 7h 15m
- 6h 50m 15s
- 2h 5s
- 0.1s
如果不想要空格,只需删除replaceAll
即可。
发布于 2013-04-25 23:45:55
Apache commons-lang提供了一个有用的类来实现这一点,DurationFormatUtils
例如DurationFormatUtils.formatDurationHMS( 15362 * 1000 ) )
=> 4:16:02.000 (H:m:s.millis) DurationFormatUtils.formatDurationISO( 15362 * 1000 ) )
=> P0Y0M0DT4H16M2.000S,参见。ISO8601
https://stackoverflow.com/questions/3471397
复制相似问题