显示一周日期,点击查看上下周,默认显示本周
效果
html
<span onclick="GetPreWeekRange()" class="weekOnchange">《 上周</span>
<div class="" style="display:inline-block;float:left;" id="weekDay"></div>
<span onclick="GetNextWeekRange()" class="weekOnchange">下周 》</span>
js代码
var currentTime = new Date();
$(function () {
WeekChange()//周期
})
//本周
function WeekChange() {
var nowDayOfWeek = currentTime.getDay();//当前周的第几天
var nowDay = currentTime.getDate();//当前日
var nowMonth = currentTime.getMonth();//当前月
var nowYear = currentTime.getFullYear();//当前年
//转换成一个完整日期(计算本周开始的日期nowDay - nowDayOfWeek + 1)
//本周结束日期:new Date(nowYear, nowMonth,nowDay + (7 - nowDayOfWeek))
var surren = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
var preRange = {};
preRange.surren = surren//完整日期传给后台
GetDays(preRange)
}
//上周
function GetPreWeekRange() {
var nowDayOfWeek = currentTime.getDay();//当前周的第几天
var nowDay = currentTime.getDate();//当前日
var nowMonth = currentTime.getMonth();//当前月
var nowYear = currentTime.getFullYear();//当前年
//(上周结束日期:nowDay + (6 - nowDayOfWeek - 6))
//上周开始日期日期
var surren = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6);
var preRange = {};
preRange.surren = surren
GetDays(preRange)
}
//下周
function GetNextWeekRange() {
var nowDayOfWeek = currentTime.getDay();//当前周的第几天
var nowDay = currentTime.getDate();//当前日
var nowMonth = currentTime.getMonth();//当前月
var nowYear = currentTime.getFullYear();//当前年
//(下周结束日期:nowDay + (6 - nowDayOfWeek + 8))
//下周开始日期日期
var surren = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 8);
var preRange = {};
preRange.surren = surren
GetDays(preRange)
}
//周数
var week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]
function GetDays(preRange) {
//日期赋值成传过来的日期
currentTime = preRange.surren;
var h = "";
for (var i = 0; i < 7; i++) {
if (i == 0) {
h += "<div class='block week_active'>"
currentTime = currentTime.setDate(currentTime.getDate());//第一天不需要+1
} else {
h += "<div class='block'>"
currentTime = currentTime.setDate(currentTime.getDate() + 1);
}
currentTime = new Date(currentTime);//保存已经+了的日期
currentDays = currentTime.getDate();//日期 几号
currentMon = currentTime.getMonth() + 1;//几月
h += "<span>" + week[i] + "</span></br><span>" + currentMon + "-" + currentDays + "</span>";
h += "</div>"
}
$('#weekDay').html(h)
currentTime = preRange.surren;
}