本文是对《【JavaScript】一个同步于本地时间的动态时间》一文(点击打开链接)的改进
JavaScript里面的Date类型除了可以直接toLocaleString(),转化成一个以系统格式的时间之外
还可以时间自定义格式,比如可以构造于一个仿QQ聊天框的同步于本地时间的动态时钟
具体代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>自定义时钟</title>
</head>
<body>
<div style='text-align:center'><font id='clock' size='2' color='#666666'></font></div>
</body>
</html>
<script>
setInterval("clock()",1000);
function clock(){
var nowTime=new Date();
var nowYear=nowTime.getFullYear().toString();
var nowMonth=nowTime.getMonth().toString();
if(nowMonth<10){
nowMonth="0"+nowMonth;
}
var nowDate=nowTime.getDate().toString();
if(nowDate<10){
nowDate="0"+nowDate;
}
var nowHours=nowTime.getHours().toString();
var nowMinutes=nowTime.getMinutes().toString();
if(nowMinutes<10){
nowMinutes="0"+nowMinutes;
}
var nowSecond=nowTime.getSeconds().toString();
if(nowSecond<10){
nowSecond="0"+nowSecond;
}
document.getElementById("clock").innerHTML=nowYear+"/"+nowMonth+"/"+nowDate+" "+nowHours+":"+nowMinutes+":"+nowSecond;
}
</script>
思想与《【JavaScript】一个同步于本地时间的动态时间》一文(
点击打开链接)完全相同,关键是setInterval函数,同时,之所以要加上各类少于10的条件结构,是因为,如果不加的话,比如19:01:01会变成19:1:1不符合我们的习惯。