Java Millisecond Format formatElapsedMillis(long time)

Here you can find the source of formatElapsedMillis(long time)

Description

Formats a time in milleseconds (typically elapsed time) into a string with format "[d'd'] hh:mm:ss.mmmm".

License

Open Source License

Declaration

public static String formatElapsedMillis(long time) 

Method Source Code

//package com.java2s;
/*/*from  www.j a v  a  2s. co  m*/
 * Copyright 1998-2007 The Brookings Institution, NuTech Solutions,Inc., Metascape LLC, and contributors. 
 * All rights reserved.
 * This program and the accompanying materials are made available solely under the BSD license "ascape-license.txt".
 * Any referenced or included libraries carry licenses of their respective copyright holders. 
 */

public class Main {
    /**
     * Formats a time in milleseconds (typically elapsed time) into a string with format "[d'd'] hh:mm:ss.mmmm".
     * For example,  00:00:02.3328, or 1d 02:12:03.3521.
     * Note that time will be downcast to an int, but this should not really be a problem!
     */
    public static String formatElapsedMillis(long time) {
        int timeInt = (int) time;
        int mils = timeInt % 1000;
        timeInt /= 1000;
        int secs = timeInt % 60;
        timeInt /= 60;
        int mins = timeInt % 60;
        timeInt /= 60;
        int hours = timeInt % 24;
        timeInt /= 24;
        //timeInt is now remaining days.
        if (timeInt == 0) {
            return Integer.toString(hours) + ":" + Integer.toString(mins) + ":" + Integer.toString(secs) + "."
                    + padStringLeftWithZeros(Integer.toString(mils), 3);
        } else {
            return Integer.toString(timeInt) + "d " + Integer.toString(hours) + ":" + Integer.toString(mins) + ":"
                    + Integer.toString(secs) + "." + padStringLeftWithZeros(Integer.toString(mils), 3);
        }
    }

    /**
     * Pads the string with spaces on the left to the supplied size.
     * If the string is larger than the supplied number of spaces it is truncated.
     * @param string the string to pad
     * @param size the size to pad (or truncate) the string to
     */
    public static String padStringLeftWithZeros(String string, int size) {
        while (string.length() < size) {
            string = '0' + string;
        }
        if (string.length() > size) {
            string = string.substring(0, size);
        }
        return string;
    }
}

Related

  1. format(long timeMillis)
  2. format(long timeMillis, String pattern)
  3. format_duration(long millis)
  4. formatCcsdsUtcMillisFormat(Date time)
  5. formatDataTimeStamp(final long timeInMillis)
  6. formatElapsedTime(long millis)
  7. formateTime(long milliseconds)
  8. formatMillis(int millis, int digits)
  9. formatMillis(long duration)