Java Hour Format formatDuration(long value)

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

Description

format Duration

License

Open Source License

Declaration

public static String formatDuration(long value) 

Method Source Code

//package com.java2s;
/*//  w  ww  .  j  a  v a  2s  .c om
 * MiscUtils.java
 *
 * Copyright (C) 2002-2015 Takis Diakoumis
 *
 * 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 3
 * of the License, or 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, see <http://www.gnu.org/licenses/>.
 *
 */

import java.text.DecimalFormat;

public class Main {
    private static DecimalFormat oneDigitFormat;
    private static DecimalFormat twoDigitFormat;

    public static String formatDuration(long value) {

        if (twoDigitFormat == null || oneDigitFormat == null) {
            oneDigitFormat = new DecimalFormat("0");
            twoDigitFormat = new DecimalFormat("00");
            //threeDigitFormat = new DecimalFormat("000");
        }

        // {"milliseconds","seconds","minutes","hours"}
        long[] divisors = { 1000, 60, 60, 24 };
        double[] result = new double[divisors.length];

        for (int i = 0; i < divisors.length; i++) {
            result[i] = value % divisors[i];
            value /= divisors[i];
        }
        /*
        String[] labels = {"milliseconds","seconds","minutes","hours"};
        for(int i = divisors.length-1;i >= 0;i--) {
           System.out.print(" " + result[i] + " " + labels[i]);
        }
        System.out.println();
        */

        //build "hh:mm:ss.SSS"
        StringBuilder buffer = new StringBuilder(" ");
        buffer.append(oneDigitFormat.format(result[3]));
        buffer.append(':');
        buffer.append(twoDigitFormat.format(result[2]));
        buffer.append(':');
        buffer.append(twoDigitFormat.format(result[1]));
        buffer.append('.');
        buffer.append(twoDigitFormat.format(result[0]));

        return buffer.toString();
    }
}

Related

  1. formatDateToStr(String format, Date date)
  2. formatDateToString(java.util.Date date, int format)
  3. formatDebugMessage(String debugLevel, Object msg)
  4. formatDicomTime(String dicomTime)
  5. formatDuration(long duration)
  6. formateDataC(Date date)
  7. formateDate(Date date)
  8. formateDate(Date date, String format)
  9. forMateDate(String dateStr)