Convert milli seconds To Time String - Android java.util

Android examples for java.util:Date Convert

Description

Convert milli seconds To Time String

Demo Code

import android.annotation.TargetApi;
import android.os.Build;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

public class Main{

    public static String millisecondsToTimeString(long milliseconds,
            boolean includeMilliseconds) {

        return millisecondsToTimeString(milliseconds, includeMilliseconds,
                true);//from  w w w  .j  av  a 2 s .co m
    }
    public static String millisecondsToTimeString(long milliseconds,
            boolean includeMilliseconds, boolean highPrecision) {

        int secondsIn = (int) Math.ceil(milliseconds / 1000);
        int millisecondsIn = ((int) milliseconds - (secondsIn * 1000));

        int hours = secondsIn / 3600;
        int remainder = secondsIn % 3600;
        int minutes = remainder / 60;
        int seconds = remainder % 60;

        // use StringBuilder for efficiency?
        return (hours > 0 ? hours + ":" : "")
                + (hours > 0 ? String.format(int2sd, minutes) : minutes)
                + ":"
                + String.format(int2sd, seconds)
                + (includeMilliseconds ? "."
                        + (highPrecision ? String.format(int3sd,
                                millisecondsIn) : String.format(int1sd,
                                millisecondsIn / 100)) : "");
    }

}

Related Tutorials