Java Duration to durationToString(Duration d)

Here you can find the source of durationToString(Duration d)

Description

duration To String

License

Open Source License

Declaration

public static String durationToString(Duration d) 

Method Source Code


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

import java.time.Duration;

public class Main {
    public static String durationToString(Duration d) {
        String s = "";
        boolean started = false;
        if (d.toDays() >= 365) {
            started = true;/*from w  w  w.j av a 2  s .c  om*/
            s += d.toDays() / 365 + " year" + ((d.toDays() / 365 != 1) ? "s" : "") + ", ";
            d = d.minus(Duration.ofDays(d.toDays() / 365 * 365));
        }
        if (started || d.toDays() >= 30) {
            started = true;
            s += d.toDays() / 30 + " month" + ((d.toDays() / 30 != 1) ? "s" : "") + ", ";
            d = d.minus(Duration.ofDays(d.toDays() / 30 * 30));
        }
        if (started || d.toDays() >= 7) {
            started = true;
            s += d.toDays() / 7 + " week" + ((d.toDays() / 7 != 1) ? "s" : "") + ", ";
            d = d.minus(Duration.ofDays(d.toDays() / 7 * 7));
        }
        if (started || d.toDays() > 0) {
            started = true;
            s += d.toDays() + " day" + ((d.toDays() != 1) ? "s" : "") + ", ";
            d = d.minus(Duration.ofDays(d.toDays()));
        }
        if (started || d.toHours() > 0) {
            s += d.toHours() + " hour" + ((d.toHours() != 1) ? "s" : "") + ", ";
            started = true;
            d = d.minus(Duration.ofHours(d.toHours()));
        }
        if (started || d.toMinutes() > 0) {
            s += d.toMinutes() + " minute" + ((d.toMinutes() != 1) ? "s" : "") + " and ";
            started = true;
            d = d.minus(Duration.ofMinutes(d.toMinutes()));
        }
        if (started || d.getSeconds() > 0) {
            s += d.getSeconds() + " second" + ((d.getSeconds() != 1) ? "s" : "");
        }
        return s;
    }
}

Related

  1. durationToFloat(Duration duration)
  2. toDuration(Long unixTime)
  3. toDuration(String durationString)
  4. toMicro(Duration duration)
  5. toSeconds(final Duration time)