Javascript每周计算日期

时间:2015-07-27 12:55:32

标签: javascript date

嗨伙计们, 我已经逐步编写了这个javascript代码,用于计算任何一天的日期。 但是,当代码必须计算月末时,我会出现错误:例如,在31/07 / 2'15之后,代码生成32/07/2015而不是01/08/2015。 这是我的代码:

var application = this;
        var currentDate = new Date();
        var stringDate1 = currentDate.getUTCDate() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate2 = (currentDate.getUTCDate()+1) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate3 = (currentDate.getUTCDate() + 2) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate4 = (currentDate.getUTCDate() + 3) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate5 = (currentDate.getUTCDate() + 4) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate6 = (currentDate.getUTCDate() + 5) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
        var stringDate7 = (currentDate.getUTCDate() + 6) + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();

我的代码错了? 有什么帮助吗? BR

2 个答案:

答案 0 :(得分:1)

只需将hours*minutes*seconds*milliseconds添加到今天的日期,即可获得明天的日期,依此类推。

var tomorrowsDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);

答案 1 :(得分:1)

要计算提前一天的日期,您可以使用Date.prototype.setDate()

因此,要计算今天和未来一周的所有日期,您可以执行以下操作:

var currentDate = new Date();
var stringDate = [];

for (var i = 0; i < 7; ++i) {
    currentDate.setDate(currentDate.getDate() + 1);
    stringDate[i] = currentDate.getUTCDate() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
}

console.log(stringDate);

// 0: "28/7/2015"
// 1: "29/7/2015"
// 2: "30/7/2015"
// 3: "31/7/2015"
// 4: "1/8/2015"
// 5: "2/8/2015"
// 6: "3/8/2015"