Java – format for a period of time

In Java, I have a long integer that represents a period of time (in milliseconds) The time period can be any time period from a few seconds to a few weeks I want to output this time period as a string with appropriate units

For example, 3000 should output "3 seconds", 61200000 should output "17 hours", and 1814400000 should output "3 weeks"

Ideally, I can also micro tune the format of sub units. For example, 62580000 may output "17 hours and 23 minutes"

Are there any existing Java classes to handle this problem?

Solution

The joda library can do this for you:

PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
 .printZeroAlways()
 .appendYears()
 .appendSuffix(" year"," years")
 .appendSeparator(" and ")
 .printZeroRarely()
 .appendMonths()
 .appendSuffix(" month"," months")
 .toFormatter();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>