Java Duration Format formatDuration(long duration)

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

Description

format Duration

License

Apache License

Declaration

public static String formatDuration(long duration) 

Method Source Code

//package com.java2s;
/*//from   w  w w. j  a v  a2 s  .  c o  m
 * Copyright 2017 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed 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 {
    private static final long ONE_SECOND = 1000L;
    private static final long ONE_MINUTE = 60 * ONE_SECOND;
    private static final long ONE_HOUR = 60 * ONE_MINUTE;
    private static final long ONE_DAY = 24 * ONE_HOUR;

    public static String formatDuration(long duration) {
        // CHECKSTYLE_OFF: MagicNumber
        long ms = duration % 1000;
        long s = (duration / ONE_SECOND) % 60;
        long m = (duration / ONE_MINUTE) % 60;
        long h = (duration / ONE_HOUR) % 24;
        long d = duration / ONE_DAY;
        // CHECKSTYLE_ON: MagicNumber

        String format;
        if (d > 0) {
            // Length 11+ chars
            format = "%d d %02d:%02d h";
        } else if (h > 0) {
            // Length 7 chars
            format = "%2$02d:%3$02d h";
        } else if (m > 0) {
            // Length 9 chars
            format = "%3$02d:%4$02d min";
        } else {
            // Length 7-8 chars
            format = "%4$d.%5$03d s";
        }

        return String.format(format, d, h, m, s, ms);
    }
}

Related

  1. formatDuration(int seconds)
  2. formatDuration(int seconds)
  3. formatDuration(long duration)
  4. formatDuration(long duration)
  5. formatDuration(long duration)
  6. formatDuration(long duration, boolean displayMilliseconds)
  7. formatDuration(long duration, boolean simplify, boolean includeMillies)
  8. formatDuration(long durationInMs)
  9. formatDuration(long durationMillis)