Formatting a Time Period

In Java, I have a long integer representing the time period in milliseconds. The time period can be from a few seconds to several weeks. I would like to output this time period as a string with the corresponding block.

For example, 3,000 should be displayed as "3 seconds," 61,200,000 should be displayed as "17 hours," and 1,814,400,000 should be displayed as "3 weeks."

Ideally, I could also fine-tune the formatting of the sub-blocks, for example. 62,580,000 can be displayed as "17 hours, 23 minutes."

Are there any existing Java classes that handle this?

+3
source share
4 answers

Joda :

PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
 .printZeroAlways()
 .appendYears()
 .appendSuffix(" year", " years")
 .appendSeparator(" and ")
 .printZeroRarely()
 .appendMonths()
 .appendSuffix(" month", " months")
 .toFormatter();
+7
+7

Check out joda-time format

0
source
        //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();
0
source

Source: https://habr.com/ru/post/1726201/


All Articles