在Java中,我有一个长整型,表示以毫秒为单位的时间段。时间段可以是从几秒到几周的任何时间。我想用适当的单位以字符串的形式输出这段时间。格式化一段时间
例如3,000应输出为“3秒”,61,200,000应输出为“17小时”,1,814,400,000应输出为“3周”。理想情况下,我也可以微调子单元的格式,例如, 62,580,000可能会输出为“17小时23分钟”。
是否有任何现有的Java类可以处理这个问题?
在Java中,我有一个长整型,表示以毫秒为单位的时间段。时间段可以是从几秒到几周的任何时间。我想用适当的单位以字符串的形式输出这段时间。格式化一段时间
例如3,000应输出为“3秒”,61,200,000应输出为“17小时”,1,814,400,000应输出为“3周”。理想情况下,我也可以微调子单元的格式,例如, 62,580,000可能会输出为“17小时23分钟”。
是否有任何现有的Java类可以处理这个问题?
的Joda库可以为你做的:
PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears()
.appendSuffix(" year", " years")
.appendSeparator(" and ")
.printZeroRarely()
.appendMonths()
.appendSuffix(" month", " months")
.toFormatter();
退房乔达时间的format package
参见在Apache公地DurationFormatUtils。
//Something like this works good too
long period = ...;
StringBuffer sb = new StringBuffer();
sb.insert(0, String.valueOf(period % MILLISECS_IN_SEC) + "%20milliseconds");
if (period > MILLISECS_IN_SEC - 1)
sb.insert(0, String.valueOf(period % MILLISECS_IN_MIN/MILLISECS_IN_SEC) + "%20seconds,%20");
if (period > MILLISECS_IN_MIN - 1)
sb.insert(0, String.valueOf(period % MILLISECS_IN_HOUR/MILLISECS_IN_MIN) + "%20minutes,%20");
if (period > MILLISECS_IN_HOUR - 1)
sb.insert(0, String.valueOf(period % MILLISECS_IN_DAY/MILLISECS_IN_HOUR) + "%20hours,%20");
if (period > MILLISECS_IN_DAY - 1)
sb.insert(0, String.valueOf(period/MILLISECS_IN_DAY) + "%20days,%20");
return sb.toString();
这是一个丑陋的做法。 – Dariusz 2013-02-14 14:10:02