标签:
new Date(); //获取系统时间
getFullYear(); //年
getMonth()+1; //月,初始值为0
getDate(); //日
getDay(); //星期,星期日返回的值为0
getHours(); //时
getMinutes(); //分
getSeconds(); //秒
完整示例如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>操作系统时间</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 6 <script type="text/javascript"> 7 window.onload = function(){ 8 setInterval(getClock,1000); 9 10 getClock();//页面打开自动执行,防止刷新1s后才显示 11 function getClock(){ 12 var oBody = document.body; 13 var str = ""; 14 var myDate = new Date(); //获取系统时间 15 16 var iYear = myDate.getFullYear(); //年 17 var iMonth = myDate.getMonth()+1; //月,初始值为0 18 var iDate = myDate.getDate(); //日 19 var iWeek = myDate.getDay(); //星期,星期日返回的值为0 20 var iHour = myDate.getHours(); //时 21 var iMin = myDate.getMinutes(); //分 22 var iSec = myDate.getSeconds(); //秒 23 24 if(iWeek === 0) iWeek = "星期日"; 25 if(iWeek === 1) iWeek = "星期一"; 26 if(iWeek === 2) iWeek = "星期二"; 27 if(iWeek === 3) iWeek = "星期三"; 28 if(iWeek === 4) iWeek = "星期四"; 29 if(iWeek === 5) iWeek = "星期五"; 30 if(iWeek === 6) iWeek = "星期六"; 31 32 str = iYear+"年"+iMonth+"月"+iDate+"日"+ iWeek+ addZero(iHour)+":"+addZero(iMin)+":"+addZero(iSec); 33 oBody.innerHTML = str; 34 } 35 36 function addZero(n){ 37 //如果当前返回的值小于10,则给它添加一个0 38 return n<10 ? "0"+n : ""+n; 39 } 40 } 41 </script> 42 </head> 43 <body> 44 45 </body> 46 </html>
倒计时在网页中也是一种常见的效果,它的原理就是将两个时间进行比较,然后再把算出来的值进行天,时,分,秒的转化,具体的使用案例如下代码所示:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>倒计时</title> 6 <script type="text/javascript"> 7 window.onload = function(){ 8 var str=""; 9 var iNow = new Date(); //当前日期 10 var iNew = new Date(2016,7,9,0,0,0); //未来的一个时间,数字形式,月份需要当前月份-1 11 //var iNew = new Date(‘August 9,2016 0:0:0‘); 字符串形式 12 13 var t = Math.floor((iNew - iNow)/1000); //毫秒转化成秒 14 var day = Math.floor(t/86400) //获取天 15 var hours = Math.floor(t%86400/3600) //获取小时 16 var min = Math.floor(t%86400%3600/60) //获取分钟 17 var sec = Math.floor(t%60) //获取秒钟 18 19 str = "距离2016年情人节还有:"+day+"天" + hours+"小时"+ min+"分"+ sec+"秒"; 20 21 document.body.innerHTML = str; 22 } 23 </script> 24 </head> 25 <body> 26 27 </body> 28 </html>
标签:
原文地址:http://www.cnblogs.com/sese/p/5726594.html