Java时间工具--根据毫秒数按照时分秒格式“HH:mm:ss”显示

有时会有这样的需求,根据毫秒数或秒数按照时分秒格式显示出来。
比如,通话时长,从通话开始时计时到通话结束,是有毫秒数的,但是显示要按照时分秒格式显示”HH:mm:ss”,小于10的要自动在前面补0。如:【语音对讲】03:40
如下工具类可实现:


public class Time {
    public static String formatDateTime(long milliseconds) {
        StringBuilder sb = new StringBuilder();
        long mss = milliseconds / 1000;
        long days = mss / (60 * 60 * 24);
        long hours = (mss % (60 * 60 * 24)) / (60 * 60);
        long minutes = (mss % (60 * 60)) / 60;
        long seconds = mss % 60;
        DecimalFormat format = new DecimalFormat("00");
        Log.d("Time", "--days:"+days+"--hours:"+hours+"--minutes:"+minutes+"--seconds:"+seconds);
        if (days > 0 || hours > 0) {
            sb.append(format.format(hours)).append(":").append(format.format(minutes)).append(":").append(format.format(seconds));
        }else {
            sb.append(format.format(minutes)).append(":").append(format.format(seconds));
        }

        Log.d("Time", "--data:"+sb.toString());
        return sb.toString();
    }

}

你可能感兴趣的:(工具类)