Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说将毫秒转成时:分:秒[亲测有效],希望能够帮助你!!!。
首先,需要知道是如何求时分秒的:
设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)); }*/
}
今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
上一篇
已是最后文章
下一篇
已是最新文章