Java TimeUnit Format formatMinutesSeconds(final long sourceDuration, final TimeUnit sourceUnit)

Here you can find the source of formatMinutesSeconds(final long sourceDuration, final TimeUnit sourceUnit)

Description

Formats the specified duration in 'mm:ss.SSS' format.

License

Apache License

Parameter

Parameter Description
sourceDuration the duration to format
sourceUnit the unit to interpret the duration

Return

representation of the given time data in minutes/seconds

Declaration

public static String formatMinutesSeconds(final long sourceDuration, final TimeUnit sourceUnit) 

Method Source Code

//package com.java2s;
/**/*w  w  w .  j ava 2s .  c  o m*/
 * Copyright (C) 2016 Hurence (support@hurence.com)
 *
 * 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.
 */

import java.util.concurrent.TimeUnit;

public class Main {
    /**
     * Formats the specified duration in 'mm:ss.SSS' format.
     *
     * @param sourceDuration the duration to format
     * @param sourceUnit the unit to interpret the duration
     * @return representation of the given time data in minutes/seconds
     */
    public static String formatMinutesSeconds(final long sourceDuration, final TimeUnit sourceUnit) {
        final long millis = TimeUnit.MILLISECONDS.convert(sourceDuration, sourceUnit);

        final long millisInMinute = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);
        final int minutes = (int) (millis / millisInMinute);
        final long secondsMillisLeft = millis - minutes * millisInMinute;

        final long millisInSecond = TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS);
        final int seconds = (int) (secondsMillisLeft / millisInSecond);
        final long millisLeft = secondsMillisLeft - seconds * millisInSecond;

        return pad2Places(minutes) + ":" + pad2Places(seconds) + "." + pad3Places(millisLeft);
    }

    private static String pad2Places(final long val) {
        return (val < 10) ? "0" + val : String.valueOf(val);
    }

    private static String pad3Places(final long val) {
        return (val < 100) ? "0" + pad2Places(val) : String.valueOf(val);
    }
}

Related

  1. format(final long duration, final TimeUnit sourceUnit, final TimeUnit min)
  2. formatDuration(long time, TimeUnit unit)
  3. formatHighest(long duration, final TimeUnit max)
  4. formatMillis(long duration, TimeUnit max, TimeUnit min, boolean useAbbreviation)
  5. formatTime(long dt, TimeUnit input, TimeUnit output, int decimalPlaces)