详解JavaScript的Date对象(制作简易钟表)
内容摘要
JS提供了Date类型来处理时间和日期。Date类型内置一系列获取和设置日期时间信息的方法。下面我们简单的
概述一下这个Date类型。
大概看了一下Date类型的方法,下面
概述一下这个Date类型。
大概看了一下Date类型的方法,下面
文章正文
JS提供了Date类型来处理时间和日期。Date类型内置一系列获取和设置日期时间信息的方法。下面我们简单的
概述一下这个Date类型。
大概看了一下Date类型的方法,下面给出:
上面的方法自己尝试即可,我只简单的演示一下JS正确输出的格式:
1 2 3 4 5 6 7 | 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/>" ); |
输出的结果为:
看到这里我就想到了电脑自带的本地时钟,单击任务栏上的时间,会弹出来一个钟表:
那么我们既然知道了JS中的Date类型,是否我们可以在网页上显示一个本地时间和日期的钟表,由于学习的JS知
识少,我就简单地做了一个简易钟表。
给出代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | <!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 (); //获取当前时间的日期 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[d+1]+ " " +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> |
看一下运行的结果:
通过在制作简单的钟表效果,学习JavaScript的Date对象,加深对Date对象的认识,希望对大家的学习有所帮助。
代码注释