Java Duration Format durationToString(long durationMs)

Here you can find the source of durationToString(long durationMs)

Description

Converts a time duration in milliseconds into DDD:HH:MM:SS format.

License

Apache License

Declaration

public static String durationToString(long durationMs) 

Method Source Code

//package com.java2s;
/**/*from  ww w .  j  a v  a2s  . c  o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Converts a time duration in milliseconds into DDD:HH:MM:SS format.
     */
    public static String durationToString(long durationMs) {
        boolean negative = false;
        if (durationMs < 0) {
            negative = true;
            durationMs = -durationMs;
        }
        // Chop off the milliseconds
        long durationSec = durationMs / 1000;
        final int secondsPerMinute = 60;
        final int secondsPerHour = 60 * 60;
        final int secondsPerDay = 60 * 60 * 24;
        final long days = durationSec / secondsPerDay;
        durationSec -= days * secondsPerDay;
        final long hours = durationSec / secondsPerHour;
        durationSec -= hours * secondsPerHour;
        final long minutes = durationSec / secondsPerMinute;
        durationSec -= minutes * secondsPerMinute;
        final long seconds = durationSec;
        final long milliseconds = durationMs % 1000;
        String format = "%03d:%02d:%02d:%02d.%03d";
        if (negative) {
            format = "-" + format;
        }
        return String.format(format, days, hours, minutes, seconds,
                milliseconds);
    }
}

Related

  1. durationToSec(int millis)
  2. durationToString(final long msec)
  3. durationToString(int millis)
  4. durationToString(long durationInMilliSeconds)
  5. durationToString(long durationInMillisLong)
  6. durationToString(Long ms)
  7. durationToString(long x)
  8. durationTranslator(String sonarDuration)
  9. format8601Duration(long duration)