周视图日历计算方法
程序员文章站
2022-05-07 21:55:46
...
代码
function WeekLayoutCalendar() {
//当前周
var cells = document.getElementById('currWeek').getElementsByTagName('div');
//周长度
var clen = cells.length;
console.log(clen);
//当前周的第一天
var currentFirstDate;
//new两个当天
var myDate = new Date();
var etDate = new Date();
//当前天的日期的日
today = myDate.getDate();
console.log(today);
var formatDate = function (date) {
var year = date.getFullYear() + '年';
var month = (date.getMonth() + 1) + '月';
var day = date.getDate();
return day;
};
var addDate = function (date, n) {
date.setDate(date.getDate() + n);
return date;
};
var setDate = function (date) {
var week = date.getDay();
date = addDate(date, week * -1);
currentFirstDate = new Date(date);
var currM = currentFirstDate.getMonth();
var todayM = myDate.getMonth();
document.getElementById('currYM').innerHTML = currentFirstDate.getFullYear() + '-' + (1 + currentFirstDate.getMonth() < 10 ? '0' + parseInt(1 + currentFirstDate.getMonth()) : 1 + currentFirstDate.getMonth());
myDate.setDate(myDate.getDate() - myDate.getDay());
for (var i = 0; i < clen; i++) {
cells[i].innerHTML = formatDate(i == 0 ? date : addDate(date, 1));
if (cells[i].innerHTML == today && currentFirstDate.getMonth() == myDate.getMonth() && currentFirstDate.getFullYear() == myDate.getFullYear()) {
cells[i].className = 'curr-day';
document.getElementById('currYM').innerHTML = myDate.getFullYear() + '-' + (1 + etDate.getMonth() < 10 ? '0' + parseInt(1 + etDate.getMonth()) : 1 + etDate.getMonth());
}
else {
cells[i].className = '';
}
}
};
document.getElementsByClassName('button-prev')[0].onclick = function () {
setDate(addDate(currentFirstDate, -7));
};
document.getElementsByClassName('button-next')[0].onclick = function () {
setDate(addDate(currentFirstDate, 7));
};
setDate(new Date());
};