关于时间日常项目中可能会有很多需求,今天就写一个最简单的,将系统时间写入到页面上。直接来看js代码:
<script> window.onload=function(){ var Body=document.body; //把获取出的时间封装为一个函数,方便加定时器让其自动循环 function Time(){ var str=""; var myTime=new Date(); var iYear = myTime.getFullYear(); var iMonth = myTime.getMonth()+1; var iDate = myTime.getDate(); var iWeek = myTime.getDay(); var iHours = myTime.getHours(); var iMin = myTime.getMinutes(); var iSec = myTime.getSeconds(); //getDay是从0开始的,所以要判断星期 if( iWeek === 0 ) iWeek = ‘星期日‘; if( iWeek === 1 ) iWeek = ‘星期一‘; if( iWeek === 2 ) iWeek = ‘星期二‘; if( iWeek === 3 ) iWeek = ‘星期三‘; if( iWeek === 4 ) iWeek = ‘星期四‘; if( iWeek === 5 ) iWeek = ‘星期五‘; if( iWeek === 6 ) iWeek = ‘星期六‘; str = iYear+ ‘年‘ +iMonth+‘月‘+iDate+‘日 ‘+iWeek+‘ ‘+ toTwo(iHours)+‘ : ‘+ toTwo(iMin)+‘ : ‘+ toTwo(iSec); Body.innerHTML=str; } //加定时器,自动循环 setInterval(Time,1000); Time(); }; //这里对单数0-9的判断,让其前面加0 function toTwo ( n ) { return n < 10 ? ‘0‘ + n : ‘‘ + n; } </script>
这样就可以了,具体该注意的地方在注释上已经写清楚了。最简单的写法希望对大家有帮助!
原文地址:https://www.cnblogs.com/web001/p/8137545.html
时间: 2024-11-09 02:55:14