<div id="date_box"></div>
var d = new Date();
var year = d.getFullYear(); //年份
var month = d.getMonth(); //第几个月
var date = d.getDate(); //几号
var startYear = 2000;
var endYear = 2020;
var years = 2020 - 2000;
var getDays = function(year, month){return (new Date(year, month, 0)).getDate();};
var getWeekDay = function(year, month, date){return (new Date(year, month, date)).getDay();}
var dateBox = document.getElementById('date_box');
var dateHead = document.createElement('div');
dateHead.setAttribute('id', 'date_head')
dateBox.appendChild(dateHead);
var dateBody = document.createElement('div');
dateBody.setAttribute('id', 'date_body')
dateBox.appendChild(dateBody);
//显示年份
var yearSelector = document.createElement('select');
for(var i=0; i<years; i++){
var curYear = startYear + i;
var newOption = document.createElement('option');
newOption.setAttribute('value', curYear);
newOption.innerHTML = curYear;
yearSelector.appendChild(newOption)
}
dateHead.appendChild(yearSelector); //添加年份
yearSelector.onchange = function(){
setWeekTable(this.value, 0);
var optionArr = monthEle.getElementsByTagName('option');
optionArr[0].selected = true;
}
//显示月份
var monthEle = document.createElement('select');
for(var i=0; i<12; i++){
var newOption = document.createElement('option');
newOption.setAttribute('value', i);
newOption.innerHTML = i+1;
monthEle.appendChild(newOption)
}
dateHead.appendChild(monthEle); //添加月份
monthEle.onchange = function(){
setWeekTable(year, this.value)
}
//显示日期
function setWeekTable(year, month){
var days = getDays(year, month);
var weekDay = getWeekDay(year, month, 1);
var count = 0;
var daysTable = '<table><tr><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr><tr>'
for(var j=0; j<weekDay; j++){
daysTable += '<td></td>'
}
for(var i=0; i<days; i++){
if((count + weekDay + i)%7 == 0){
daysTable += '</tr></tr>'
}
daysTable += '<td>'+(i+1)+'</td>'
}
daysTable += '</tr></table>'
dateBody.innerHTML = daysTable;
}
setWeekTable(year, month);