Java Duration Format formatDuration(long durationMillis)

Here you can find the source of formatDuration(long durationMillis)

Description

format Duration

License

Open Source License

Parameter

Parameter Description
durationMillis a length of time in milliseconds.

Return

a nicely formatted string representation of that duration.

Declaration

public static String formatDuration(long durationMillis) 

Method Source Code

//package com.java2s;
/* Copyright (C) 2007 The Open University
    /*from  ww  w.jav a2  s .  c om*/
   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.
    
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
    
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

public class Main {
    private static final long SECOND = 1000;
    private static final long MINUTE = 60 * SECOND;
    private static final long HOUR = 60 * MINUTE;
    private static final long DAY = 24 * HOUR;

    /**
     * @param durationMillis a length of time in milliseconds.
     * @return a nicely formatted string representation of that duration.
     */
    public static String formatDuration(long durationMillis) {
        long[] intervals = new long[] { SECOND, MINUTE, HOUR, DAY };
        String[] words = new String[] { " second", " minute", " hour", " day" };

        StringBuffer result = new StringBuffer(100);
        boolean started = false;
        for (int i = intervals.length - 1; i >= 0; i--) {
            long num = durationMillis / intervals[i];
            if (num > 0) {
                if (started) {
                    result.append(", ");
                }
                result.append(num);
                result.append(words[i]);
                if (num > 1) {
                    result.append('s');
                }
                started = true;
                durationMillis -= num * intervals[i];
            }
        }

        return result.toString();
    }
}

Related

  1. formatDuration(long duration)
  2. formatDuration(long duration)
  3. formatDuration(long duration, boolean displayMilliseconds)
  4. formatDuration(long duration, boolean simplify, boolean includeMillies)
  5. formatDuration(long durationInMs)
  6. formatDuration(long durationSec)
  7. formatDuration(long elapsed)
  8. formatDuration(long elapsedSec)
  9. formatDuration(Long input)