JavaScript Date(日期)對象
日期格式化,簡單倒計時
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<script type="text/javascript">
const byTime = [12*30*24*60*60*1000,30*24*60*60*1000,24*60*60*1000,60*60*1000,60*1000,1000];
const unit = ["年","月","日","時","分","秒"];
function str(){
let a = new Date("2016-10-01 00:00:00");
let ct = new Date().getTime() - a.getTime();
if(ct<0){
return
}
let sb = [];
for(let i=0;i<byTime.length;i++){
let temp = Math.floor(ct/byTime[i]);
ct = ct % byTime[i];
if(temp>0){
sb.push(temp+unit[i]);
}
}
console.log("距離 "+format(a)+" 已經過去 "+sb.join("")+" 了");
}
function format(a) {
let time = a.getTime();
let y = a.getFullYear();
let m = a.getMonth()+1;
let d = a.getDate();
let h = a.getHours();
h = h < 10 ? "0"+h : h;
let min = a.getMinutes();
min = min < 10 ? "0"+min : min;
let s = a.getSeconds();
s = s < 10 ? "0"+s : s;
return y+"年"+m+"月"+d+"日"+h+":"+min+":"+s;
}
setInterval(str, 1000);
// str(new Date("2016-10-01 00:00:00"))
//距離 2016年10月1日00:00:00 已經過去 13日15時2分29秒 了
//距離 2016年10月1日00:00:00 已經過去 13日15時2分30秒 了
</script>
</body>
</html>