我怎么能“漂亮地打印” Java中的持续时间? [英] How can I "pretty print" a Duration in Java?

查看:136
本文介绍了我怎么能“漂亮地打印” Java中的持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道一个Java库可以在几分之一的时间内以与C#相同的方式打印一个数字?

Does anyone know of a Java library that can pretty print a number in milliseconds in the same way that C# does?

例如,长123456毫秒将是打印为4d1h3m5s。

E.g., 123456 ms as a long would be printed as 4d1h3m5s.

推荐答案

Joda Time 有一个非常好的方法来使用 PeriodFormatterBuilder

Joda Time has a pretty good way to do this using a PeriodFormatterBuilder.

Quick Win: PeriodFormat.getDefault()。print(duration.toPeriod()) ;

Quick Win: 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);

这篇关于我怎么能“漂亮地打印” Java中的持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆