从日历中获取上一周和下周(Javascript)

时间:2015-06-12 01:28:51

标签: javascript calendar

我想做一个周计划,它显示一周中的所有日子和相应的日期。当然还有这个月。

(很遗憾,我没有足够的声誉来发布我日历的截图。)

我的javascript代码看起来像这样。我从StackOverflow中找到了它的一部分。 (谢谢,Delan Azabani!)

function calendar() {
    var today = new Date();
    var currYear = today.getFullYear();
    var currMonth = today.getMonth();
    var currWeek = today.getWeek()-1;

    var firstDateOfMonth = new Date(currYear, currMonth, 1);
    var firstDayOfMonth = firstDateOfMonth.getDay();    

    var firstDateOfWeek = new Date(firstDateOfMonth);

    firstDateOfWeek.setDate(
        firstDateOfWeek.getDate() +
        (firstDayOfMonth ? 7 - firstDayOfMonth : 0)
    );

    firstDateOfWeek.setDate(
        firstDateOfWeek.getDate() +
        7 * (currWeek-1)
    );


    var dateNumbersOfMonthOnWeek = [];
    var datesOfMonthOnWeek = [];

    for (var i = 0; i < 7; i++) {

        dateNumbersOfMonthOnWeek.push(
            firstDateOfWeek.getDate());

        datesOfMonthOnWeek.push(
            new Date(+firstDateOfWeek));

        firstDateOfWeek.setDate(
            firstDateOfWeek.getDate() + 1);

    }

    setText('month-year', monthArray[currMonth] + " " + currYear);

    setText('Mo', dateNumbersOfMonthOnWeek[0]);
    setText('Di', dateNumbersOfMonthOnWeek[1]);
    setText('Mi', dateNumbersOfMonthOnWeek[2]);
    setText('Do', dateNumbersOfMonthOnWeek[3]);
    setText('Fr', dateNumbersOfMonthOnWeek[4]);
    setText('Sa', dateNumbersOfMonthOnWeek[5]);
    setText('So', dateNumbersOfMonthOnWeek[6]);

};


function setText(id, val) {
    if(val < 10){
        val = '0' + val;
    }
    document.getElementById(id).innerHTML = val;

};


window.onload = calendar;

它起作用,因为它显示工作日的正确日期(因此,本周一为08,本周二为09等),月份也是正确的日期。

现在的问题是如何获得前一周或下周?当我点击“&lt;” arrow我想看前一周。那么我应该如何处理循环,该方法需要哪些参数等等...我非常感谢每个提示,链接,示例等!!

周末愉快!

1 个答案:

答案 0 :(得分:0)

下周 -

var today = new Date();
var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7);

有关详细信息,请查看以下链接: -

how to get next week date in javascript