3 回答
TA贡献358条经验 获得超213个赞
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>当前时间为:<span id="time"></span></div>
<script>
function formatDate(date, flag) {
date = date ? new Date(date) : new Date();
var y = date.getFullYear();
var m = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
var d = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
var h = date.getHours() > 9 ? date.getHours() : '0' + date.getHours();
var M = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes();
var s = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
if (!flag) {
return (y + ' 年 ' + m + ' 月 ' + d + ' 日 ' + h + ' 时 ' + M + ' 分 ' + s + ' 秒');
} else if (flag === 'M') {
return (y + '-' + m);
} else if (flag === 'D') {
return (y + '-' + m + '-' + d);
}
}
var time = document.querySelector('#time');
time.innerHTML = formatDate();
setInterval(function() {
time.innerHTML = formatDate();
}, 1000);
</script>
</body>
</html>
TA贡献25条经验 获得超10个赞
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>时间</title> <script type="text/javascript"> function myTime() { var dt=new Date(); var year=dt.getFullYear(); var month=dt.getMonth()+1; var date=dt.getDate(); var hours=dt.getHours(); var minutes=dt.getMinutes(); var seconds=dt.getSeconds(); //判断上午下午 var time="AM"; if(hours>12){ time="PM"; hours=hours-12; } //判断星期 var day=dt.getDay(); var week=""; switch (day){ case 0: week="星期日"; break; case 1: week="星期一"; break; case 2: week="星期二"; break; case 3: week="星期三"; break; case 4: week="星期四"; break; case 5: week="星期五"; break; case 6: week="星期六"; break; } /*var ss=""; if(seconds<10){ ss+="0"+seconds; }else{ ss=seconds; }*/ var s=(seconds<10)?"0"+seconds:seconds;//三元运算 var div=document.getElementById("clock"); div.innerHTML=year+"年"+month+"月"+date+"日 "+hours+":"+minutes+":"+s+" "+time+" "+week; //setTimeout("myTime()",1000); } //setInterval("myTime()",1000); var intval=setInterval("myTime()",1000); </script> </head> <body onload="myTime()"> 当前时间:<div id="clock"></div> <input type="button" value="停止" onclick="javascript:clearInterval(intval)"/> </body> </html>
添加回答
举报