日 | 一 | 二 | 三 | 四 | 五 | 六 |
---|
<script><br> /*<br> * 获取指定年月份的日期总天数<br> * 显示的月份的第一天是星期几?<br> * */</p>
<p>var yearSelectElement = document.querySelector('#yearSelect');<br> var monthSelectElement = document.querySelector('#monthSelect');<br> var tbody = document.querySelector('tbody');<br> var strongElement = document.querySelector('strong');</p>
<p>var nowDate = new Date();</p>
<p>/*<br> * 动态生成option<br> * */<br> var html = '';<br> for (var i=1970; i<2100; i++) {<br/> if (i == nowDate.getFullYear()) {<br/> html = '<option selected>'+ i +'</option>' + html;<br> } else {<br> html = '<option>'+ i +'</option>' + html;<br> }</p>
<p>}<br> yearSelectElement.innerHTML = html;</p>
<p>var html = '';<br> for (var i=0; i<12; i++) {<br/> if (i == nowDate.getMonth()) {<br/> html += '<option value="'+i+'" selected>'+ (i+1) +'</option>';<br> } else {<br> html += '<option value="'+i+'">'+ (i+1) +'</option>';<br> }</p>
<p>}<br> monthSelectElement.innerHTML = html;</p>
<p>/*<br> * 默认显示当前年和月的日历<br> * */<br> calendar(nowDate.getFullYear(), nowDate.getMonth());</p>
<p>/*<br> * 根据选择的年和月重新生成日历<br> * */<br> yearSelectElement.onchange = monthSelectElement.onchange = function() {<br> calendar(yearSelectElement.value, monthSelectElement.value);<br> };</p>
<p>function calendar(year, month) {<br> year = Number(year);<br> month = Number(month);<br> strongElement.innerHTML = year + '年' + (month+1) + '月';</p>
<p>var html = '<tr>';<br> for (var i=1; i<=42; i++) {</p>
<p>if (i%7 == 1 && i != 1) {<br> html += '</tr><tr>';<br> }</p>
<p>var v = i- getFirstDay(year, month);</p>
<p>if (v < 1 || v > getDays(year, month)) {<br> html += '<td> </td>';<br> } else {<br> if (i % 7 == 1 || i % 7 == 0) {<br> html += '<td style="color: red">'+ v +'</td>';<br> } else if (<br> year == nowDate.getFullYear()<br> &&<br> month == nowDate.getMonth()<br> &&<br> v == nowDate.getDate()<br> ) {<br> html += '<td style="background: red; color:white;">'+ v +'</td>';<br> } else {<br> html += '<td>'+ v +'</td>';<br> }<br> }</p>
<p><br> }<br> html += '</tr>';<br> tbody.innerHTML = html;<br> }</p>
<p>/*<br> * 获取指定显示年月份的日期总天数<br> * */<br> function getDays(y, m) {<br> return new Date(y, m+1, 1, -1, 0, 0).getDate();</p>
<p>/*<br> * 得到下一月的1日,-1时0分0秒的日期<br> * -1 : 其实就是前一天,表示就是上个月的最后一天的23时<br> * */<br> var date = new Date(y, m+1, 1, -1, 0, 0);<br> /*<br> * 上个月最后一天的日期其实就是上个月总的天数<br> * */<br> return date.getDate();<br> }</p>
<p>/*<br> * 获取指定显示的年月份的第一天是星期几<br> * */<br> function getFirstDay(y, m) {<br> return new Date(y, m, 1).getDay();<br> }<br></script>
The above is the detailed content of Date functions and flexible use of function encapsulation. For more information, please follow other related articles on the PHP Chinese website!