将毫秒转成时:分:秒

首先,需要知道是如何求时分秒的:

设t=3600000毫秒,已知1秒=1000毫秒,那么转时分秒格式时,时、分、秒对应的数字分别是多少?
解:
求秒:因为1分钟=60秒,且1秒=1000毫秒
     所以(t % (60*1000) ) / 1000的结果就是对应的秒
求分:因为1分钟=60秒,1小时=60分钟,且1秒=1000毫秒
     所以(t % (60*60*1000)) / (60*1000)的结果就是对应的分
求时:同理(t / (60*60*1000))的结果就是对应的时

t毫秒对应的时分秒是:
int hours = t / 3600000;
int minutes = (t % 3600000) / 60000;
int seconds = (t % 60000 ) / 1000;

要求: 
若时间不足一分钟,格式为:59秒 
若时间大于等于一分钟,但不足一小时,格式为:59:59 、01:00 
若时间大于等一小时,格式为:01:00:00、120:03:12 
代码如下:

/**
 * 将毫秒格式化成 天:小时:分:秒
 * @author Peter(张春玲)
 *
 */
public class FormatDuration {   

    private static String getString(int t){
        String m="";
        if(t>0){
            if(t<10){
                m="0"+t;
            }else{
                m=t+"";
            }
        }else{
            m="00";
        }
        return m;
    }

    /**
     * 
     * @param t 毫秒
     * @return
     * @author Peter(张春玲)
     */
    public static String format(int t){
        if(t<60000){
            return (t % 60000 )/1000+"秒";
        }else if((t>=60000)&&(t<3600000)){
            return getString((t % 3600000)/60000)+":"+getString((t % 60000 )/1000);
        }else {
            return getString(t / 3600000)+":"+getString((t % 3600000)/60000)+":"+getString((t % 60000 )/1000);
        }
    }

   /* public static void main(String[] args) {//测试      
        System.out.println(FormatDuration.format(3600000));
    }*/
}

猜你喜欢

转载自blog.csdn.net/qq_29272491/article/details/80475788