需求
输出当前日期在页面上,日期不断更新。
提示:以下是本篇文章正文内容,下面案例可供参考
分析
- 首先获取日期对象,赋值给变量newTime;
- 通过getFullYear()等方法得到当前年月日时分秒;
- 得到的月份默认为从0月开始,就是中国的一月份,所以要把得到的月份加1输出。
- 得到的星期是从1开始,到6结束,周日是0;所以定义一个数组,数组第一个值是日,按下标输出。
- 时分秒输出时,如果小于10,就会输出1,我们要的效果时01,所以加一个判断
代码
代码如下(示例):
window.onload &#61; function() {var p &#61; document.getElementsByTagName(&#39;p&#39;)[0];var arr &#61; [&#39;日&#39;, &#39;一&#39;, &#39;二&#39;, &#39;三&#39;, &#39;四&#39;, &#39;五&#39;, &#39;六&#39;]var newtime;var years, months, dates, days, hours, minutes, seconds;setInterval(getNow, 1000);function getNow() {newtime &#61; new Date();years &#61; newtime.getFullYear();months &#61; newtime.getMonth() &#43; 1;dates &#61; newtime.getDate();days &#61; newtime.getDay();console.log(days);hours &#61; newtime.getHours();hours &#61; hours < 10 ? &#39;0&#39; &#43; hours : hours;minutes &#61; newtime.getMinutes();minutes &#61; minutes < 10 ? &#39;0&#39; &#43; minutes : minutes;seconds &#61; newtime.getSeconds();seconds &#61; seconds < 10 ? &#39;0&#39; &#43; seconds : seconds;p.innerHTML &#61; &#39;今天是&#39; &#43; years &#43; &#39;年&#39; &#43; months &#43; &#39;月&#39; &#43; dates &#43; &#39;号&#39; &#43; &#39;星期&#39; &#43; arr[days] &#43; " " &#43; hours &#43; &#39;:&#39; &#43; minutes &#43; &#39;:&#39; &#43; seconds;}