dev_
dev_

Reputation: 415

Javascript calculate date week by week

Hy guys, i have write this javascript code for calculate date for any day of week progressively. But i ahve error when the code must be calculate the end of month: example after 31/07/2'15 the code generate 32/07/2015 instead 01/08/2015. This is my code:

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();

where my code is wrong? Any help please? BR

Upvotes: 0

Views: 61

Answers (2)

Johan Karlsson
Johan Karlsson

Reputation: 6476

To calculate the date for one day ahead you can use Date.prototype.setDate()

So to calculate all dates from today and week ahead, you can do something like this:

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"

Upvotes: 1

Cos
Cos

Reputation: 1709

Just add the hours*minutes*seconds*milliseconds to today's date, and you get tomorrow's date, and so on.

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

Upvotes: 1

Related Questions