Java Second Format formatSeconds(double seconds, int precision)

Here you can find the source of formatSeconds(double seconds, int precision)

Description

format Seconds

License

Open Source License

Declaration

public static String formatSeconds(double seconds, int precision) 

Method Source Code

//package com.java2s;
/*//  w w  w .  ja v a  2s .c  o  m
 * Copyright (c) 2008, 2009, 2010, 2011 Denis Tulskiy
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with this work.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    public static String formatSeconds(double seconds, int precision) {
        int min = (int) ((Math.round(seconds)) / 60);
        int hrs = min / 60;
        if (min > 0)
            seconds -= min * 60;
        if (seconds < 0)
            seconds = 0;
        if (hrs > 0)
            min -= hrs * 60;
        int days = hrs / 24;
        if (days > 0)
            hrs -= days * 24;
        int weeks = days / 7;
        if (weeks > 0)
            days -= weeks * 7;

        StringBuilder builder = new StringBuilder();
        if (weeks > 0)
            builder.append(weeks).append("wk ");
        if (days > 0)
            builder.append(days).append("d ");
        if (hrs > 0)
            builder.append(hrs).append(":");
        if (hrs > 0 && min < 10)
            builder.append("0");
        builder.append(min).append(":");
        //        int n = precision + ((precision == 0) ? 2 : 3);
        //        String fmt = "%0" + n + "." + precision + "f";
        //        builder.append(new Formatter().format(Locale.US, fmt, seconds));
        int sec = (int) seconds;
        if (sec < 10)
            builder.append("0");
        builder.append(Math.round(sec));
        return builder.toString();
    }
}

Related

  1. formatMinutesSeconds(final long sourceDuration, final TimeUnit sourceUnit)
  2. formatNanoseconds (final long ns)
  3. formatSecondFractions(long numUnits, int denominator)
  4. formatSeconds(double seconds)
  5. formatSeconds(double seconds)
  6. formatSeconds(double value)
  7. formatSeconds(final int total)
  8. formatSeconds(int seconds)
  9. formatSeconds(int seconds)