Created
September 19, 2020 11:22
-
-
Save drmalex07/5b683f299dd97eed66a18973b1375be0 to your computer and use it in GitHub Desktop.
Format a duration in Java, #java #duration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class DurationToString | |
| { | |
| private final Duration duration; | |
| private final TimeUnit unit; | |
| private DurationToString(Duration d, TimeUnit u) | |
| { | |
| this.duration = d; | |
| this.unit = u; | |
| } | |
| public static DurationToString from(Duration d) | |
| { | |
| Objects.requireNonNull(d); | |
| return new DurationToString(d, TimeUnit.SECONDS); | |
| } | |
| public static DurationToString from(Duration d, TimeUnit u) | |
| { | |
| Objects.requireNonNull(d); | |
| Objects.requireNonNull(u); | |
| if (u.compareTo(TimeUnit.MILLISECONDS) < 0) | |
| u = TimeUnit.MILLISECONDS; | |
| else if (u.compareTo(TimeUnit.MINUTES) > 0) | |
| u = TimeUnit.MINUTES; | |
| return new DurationToString(d, u); | |
| } | |
| @Override | |
| public String toString() | |
| { | |
| final StringBuilder sb = new StringBuilder(); | |
| Duration d = this.duration; | |
| final long days = d.toDays(); | |
| if (days > 0) { | |
| sb.append(days); | |
| sb.append("days "); | |
| d = d.minusDays(days); | |
| } | |
| final long hours = d.toHours(); | |
| if (hours > 0) { | |
| sb.append(hours); | |
| sb.append("h"); | |
| d = d.minusHours(hours); | |
| } | |
| final long minutes = d.toMinutes(); | |
| if (minutes > 0 || this.unit == TimeUnit.MINUTES) { | |
| sb.append(minutes); | |
| sb.append("m"); | |
| d = d.minusMinutes(minutes); | |
| } | |
| if (this.unit == TimeUnit.MINUTES) { | |
| return sb.toString(); | |
| } | |
| final long seconds = d.getSeconds(); | |
| sb.append(seconds); | |
| sb.append("s"); | |
| if (this.unit == TimeUnit.SECONDS) { | |
| return sb.toString(); | |
| } | |
| assert(this.unit == TimeUnit.MILLISECONDS); | |
| final long millis = d.getNano() / 1_000_000; | |
| if (millis > 0) { | |
| sb.append(millis); | |
| sb.append("ms"); | |
| } | |
| return sb.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment