點選檢視一個星期的日期

Web_Notes發表於2020-09-26

顯示一週日期,點選檢視上下週,預設顯示本週
效果

在這裡插入圖片描述
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;
    }

相關文章