Java Duration Format formatDuration(Duration duration)

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

Description

Returns a formated string representation of the Duration object.

License

Open Source License

Parameter

Parameter Description
duration the Duration object to format

Return

a formated string representation of duration

Declaration

public static String formatDuration(Duration duration) 

Method Source Code


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

import java.time.Duration;

public class Main {
    /**//from  w ww  .java  2  s  . c  o  m
     * Returns a formated string representation of the {@code Duration} object.
     * Format: HH:MM:SS.
     * 
     * @see "http://stackoverflow.com/questions/266825/how-to-format-a-duration-
     *      in-java-e-g-format-hmmss"
     * @param duration
     *            the {@code Duration} object to format
     * @return a formated string representation of {@code duration}
     */
    public static String formatDuration(Duration duration) {
        long seconds = duration.getSeconds();
        long absSeconds = Math.abs(seconds);
        String positive = String.format("%d:%02d:%02d", absSeconds / 3600, (absSeconds % 3600) / 60,
                absSeconds % 60);
        return seconds < 0 ? "-" + positive : positive;
    }

    /**
     * Returns a formated string representation of {@code seconds}. Format:
     * HH:MM:SS.
     * 
     * @param seconds
     *            the duration to format in seconds
     * @return a formated string representation of {@code seconds}
     */
    public static String formatDuration(long seconds) {
        long absSeconds = Math.abs(seconds);
        String positive = String.format("%d:%02d:%02d", absSeconds / 3600, (absSeconds % 3600) / 60,
                absSeconds % 60);
        return seconds < 0 ? "-" + positive : positive;
    }
}

Related

  1. format8601Duration(long duration)
  2. formatBuildDuration(final long duration)
  3. formatDuration(double dblSeconds)
  4. formatDuration(Duration d)
  5. formatDuration(Duration duration)
  6. formatDuration(Duration duration)
  7. formatDuration(Duration duration)
  8. formatDuration(Duration duration)
  9. formatDuration(Duration duration, boolean inProgress)