Java Duration Format formatHuman(Duration duration)

Here you can find the source of formatHuman(Duration duration)

Description

format Human

License

Open Source License

Declaration

public static String formatHuman(Duration duration) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.time.*;

import java.util.Arrays;

import java.util.stream.Collectors;

public class Main {
    public static String formatHuman(Duration duration) {
        return formatHuman(duration, false);
    }/* www.j a v a  2  s .c om*/

    public static String formatHuman(Duration duration, boolean minimal) {
        Duration abs = duration.abs();
        long totalSeconds = abs.getSeconds();
        if (totalSeconds == 0) {
            return abs.toMillis() + (minimal ? "ms" : " milliseconds");
        }
        long d = totalSeconds / (3600 * 24);
        long h = (totalSeconds % (3600 * 24)) / 3600;
        long m = (totalSeconds % 3600) / 60;
        long s = totalSeconds % 60;
        String days = minimal ? compact(d, "d") : inflect(d, "day");
        String hours = minimal ? compact(h, "h") : inflect(h, "hour");
        String minutes = minimal ? compact(m, "m") : inflect(m, "minute");
        String seconds = minimal ? compact(s, "s") : inflect(s, "second");
        return Arrays.asList(days, hours, minutes, seconds).stream().filter(str -> !str.isEmpty())
                .collect(Collectors.joining(minimal ? "" : ", "));
    }

    private static String compact(long value, String suffix) {
        return (value == 0 ? "" : value + suffix);
    }

    private static String inflect(long value, String singular) {
        return (value == 1 ? "1 " + singular : (value > 1 ? value + " " + singular + "s" : ""));
    }
}

Related

  1. formatDurationAsTime(final int duration)
  2. formatDurationHMSms(long ms)
  3. formatDurationLpad(final String s)
  4. formatDurationMills(long millis)
  5. formatDurationOneUnit(long milis)
  6. formatISO8601Duration(int[] t)
  7. formatNanoDuration(final long nanos)
  8. formatPeriod(final Period period, final boolean wrapInDurationFunction)
  9. formatSeconds(Duration duration)