轻松学习JavaScript十:JavaScript的Date对象制作一个简易钟表

最后更新于:2022-04-01 11:28:46

JS提供了Date类型来处理时间和日期。Date类型内置一系列获取和设置日期时间信息的方法。下面我们简单的概述一下这个Date类型。 大概看了一下Date类型的方法,下面给出: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-28_5721558fe28a3.jpg) ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-28_57215590247fc.jpg) 上面的方法自己尝试即可,我只简单的演示一下JS正确输出的格式: ~~~ <span style="font-size:18px;"><span style="font-size:18px;"> var today=new Date();//创建一个时间日期对象 document.write("<h4>下面的是世界标准的时间输出:</h4>"); document.write(today+"<hr/>"); document.write("<h4>下面的是符合我们本地的时间输出:</h4>"); document.write(today.toLocaleString()+"<hr/>"); document.write("<h4>下面的是符合我们中国人的时间输出:</h4>"); document.write(today.getFullYear()+"-"+(today.getMonth()+1)+"-"+today.getDate()+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds()+"<hr/>");</span></span> ~~~ 输出的结果为: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-28_57215590385a5.jpg) 看到这里我就想到了电脑自带的本地时钟,单击任务栏上的时间,会弹出来一个钟表: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-28_5721559048e4f.jpg) 那么我们既然知道了JS中的Date类型,是否我们可以在网页上显示一个本地时间和日期的钟表,由于学习的JS知识少,我就简单地做了一个简易钟表。 给出代码: ~~~ <!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=gb2312" /> <title>综合实例之制作简易钟表</title> <style type="text/css"> * { margin:0px; padding:0px; outline:none; } body { background-color:#0E0E0E; overflow:hidden; } .date { width:860px; height:250px; border:1px solid #FFFFFF; margin:auto; margin-top:200px; color:#FFFFFF; } #time1 { width:860px; height:100px; margin:auto; font-size:75px; text-align:center; } #time2 { font-size:125px; text-align:center; } </style> <script type="text/javascript"> function startTime()//显示日期的函数 { var today=new Date();//创建日期时间对象 var n=today.getFullYear();//获取当前时间的年份 var m=today.getMonth();//获取当前时间的月份 var d=today.getDate();//获取一个月的某一天(1-31) var w=today.getDay();//获取一星期的某一天(0-6) var h=today.getHours();//获取当前时间的小时 var f=today.getMinutes();//获取当前时间的分钟 var s=today.getSeconds();//获取当前时间的秒钟 var weekday=new Array(7);//创建星期数组 weekday[0]="星期日"; weekday[1]="星期一"; weekday[2]="星期二"; weekday[3]="星期三"; weekday[4]="星期四"; weekday[5]="星期五"; weekday[6]="星期六"; document.getElementById('time1').innerHTML=weekday[w]+" "+n+"-"+(m+1)+"-"+checkTime(d); f=checkTime(f); s=checkTime(s); document.getElementById('time2').innerHTML=h+":"+f+":"+s; t=setTimeout('startTime()',500); } function checkTime(i)//日期校验函数 { if (i<10) { return i="0" + i; } else { return i; } } </script> </head> <!--body标签调用JS中的startTime()方法即打开网页就显示出当前年月日和时间--> <body onload="startTime()"> <!--封装整个显示日期区域--> <div class="date"> <!--显示当前年月日--> <div id="time1"></div> <!--显示当前北京时间--> <div id="time2"></div> </div> </body> </html> ~~~ 看一下运行的结果: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-28_572155905820a.jpg)          
';