Java Utililty Methods Duration Format

List of utility methods to do Duration Format

Description

The list of methods to do Duration Format are organized into topic(s).

Method

Stringduration(int len)
duration
final int hours = len / 3600;
final int minutes = len / 60 % 60;
final int seconds = len % 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
StringdurationAsString(long duration)
duration As String
StringBuilder builder = new StringBuilder();
long years = duration / millisPerYear;
duration -= years * millisPerYear;
long months = duration / millisPerMonth;
duration -= months * millisPerMonth;
long weeks = duration / millisPerWeek;
duration -= weeks * millisPerWeek;
long days = duration / millisPerDay;
...
StringdurationString(long duration)
duration String
if (duration < 0L) {
    return "N/A";
return Long.toString(duration);
StringdurationToFormattedString(final Duration duration)
Converts a Duration into a formatted String
if (duration == null) {
    return null;
return LocalTime.ofNanoOfDay(duration.toNanos()).format(DateTimeFormatter.ofPattern(DURATION_FORMAT));
intdurationToSec(int millis)
duration To Sec
return (int) ((millis / 1000) % 60);
StringdurationToString(final long msec)
duration To String
final StringBuffer sb = new StringBuffer(8);
int sec = (int) (msec / 1000);
if (sec > 60 * 60) {
    final int hours = sec / (60 * 60);
    sb.append(hours);
    sec -= hours * (60 * 60);
    sb.append(':');
final int minutes = sec / 60;
if (sb.length() > 0) {
    appendTwoDigits(sb, minutes, '0');
} else {
    sb.append(minutes);
sb.append(':');
sec -= minutes * 60;
appendTwoDigits(sb, sec, '0');
return sb.toString();
StringdurationToString(int millis)
duration To String
String seconds = "" + (int) ((millis / 1000) % 60);
int m = (int) ((millis / 1000) / 60);
if (m > 60) {
    return "";
String minutes = "" + m;
String hours = "" + (int) ((millis / 1000) / 3600);
if (seconds.length() == 1) {
...
StringdurationToString(long durationInMilliSeconds)
duration To String
long duration = durationInMilliSeconds / 1000; 
StringBuilder result = new StringBuilder();
if (duration >= MONTH) {
    final long value = duration / MONTH;
    duration -= (value * MONTH);
    result.append(value).append("month(s)");
if (duration >= DAY) {
...
StringdurationToString(long durationInMillisLong)
duration To String
double durationInMillis = (double) durationInMillisLong;
return durationToString(durationInMillis);
StringdurationToString(long durationMs)
Converts a time duration in milliseconds into DDD:HH:MM:SS format.
boolean negative = false;
if (durationMs < 0) {
    negative = true;
    durationMs = -durationMs;
long durationSec = durationMs / 1000;
final int secondsPerMinute = 60;
final int secondsPerHour = 60 * 60;
...