将时间戳格式化为 HH:ii:ss的格式
<html>
<head>
</head>
<body>
<span id="time"></span>
<script>
var timestamp = Date.parse(new Date())/1000;
var time_old = Date.parse(new Date())/1000;
timeAdd()
/**
* @purpose : 计时器,自动加一秒
* @time : 2018-01-23
* @author : daicr
*/
function timeAdd(){
document.getElementById('time').innerHTML = time_format(timestamp-time_old);
timestamp +=1;
setTimeout("timeAdd()",1000);
}
/**
* @purpose : 将时间戳格式化为 HH:ii:ss的格式
* @time : 2018-01-23
* @author : daicr
*/
function time_format(sec){
var time_str = '';
var hour = '';
var minute = '';
var second = '';
if(sec < 0){
time_str = '00:00:00';
}else if(sec < 3600){ // 一小时以内
// 分钟
minute = Math.floor(sec/60);
if(minute < 10){
minute = '0'+minute;
}
//秒
second = sec%60;
if(second < 10){
second = '0'+second;
}
time_str = '00:'+minute+':'+second;
}else{ // 一小时以上
// 小时
hour = Math.floor(sec/3600);
if(hour < 10){
hour = '0'+hour;
}
// 分钟
minute = Math.floor((sec%3600)/60);
if(minute < 10){
minute = '0'+minute;
}
//秒
second = sec%60;
if(second < 10){
second = '0'+second;
}
time_str = hour+':'+minute+':'+second;
}
return time_str;
}
</script>
</body>
</html>
本文为小作者工作中的总结,如有转载,请注明出处:http://www.cnblogs.com/chrdai/p/8336129.html