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>

本文介绍了一个使用JavaScript进行日期格式化及简单倒计时的示例代码。通过定义特定的时间基准点,该示例展示了如何计算并显示从该时间点至今所经过的具体时间,包括年、月、日、小时、分钟和秒。
1万+

被折叠的 条评论
为什么被折叠?



