简体   繁体   中英

add days to a date in a for-loop javascript

My problem is:

I want to go through an array, which has numbers in it. For each number I want to add this number as days to a certain date:

var days= ["1", "3", "4"];

$.each(days, function(key,value){

    var start = new Date(2015,01,08);

    var nextDay = new Date(start);

    console.log("start-day is:"+nextDay+ " and I should add "+value+" days");

    nextDay.setDate(start.getDate()+value);

    console.log("The next day is:"+nextDay);

});

The start-date is the 8th. of February. if the value is 1, the last log should be: "The next day is: Monday 09. February...." But the log says something like 22.April and it even changes the timezone....

If i just run it once, the result is correct (9. February). It just doesn't work in the foor loop. (I'm new to javascript)

anybody an idea? Thanks in advance, Sebi from Germany

You are passing in an array of strings not integers so you are actually adding a string to a date. There are two options

Better Option

Pass in an array of integers not an array of strings

var days= [1,3,4]; // This is an array of integers

$.each(days, function(key,value){

    var start = new Date(2015,01,08);

    var nextDay = new Date(start);

    console.log("start-day is:"+nextDay+ " and I should add "+value+" days");

    nextDay.setDate(start.getDate()+value);

    console.log("The next day is:"+nextDay);

});

Worse Option

You can parseInt() your array or make your array numbers just before you add it to the start date.

var days= ["1", "3", "4"]; // These are strings not integers

$.each(days, function(key,value){

    var start = new Date(2015,01,08);

    var nextDay = new Date(start);

    console.log("start-day is:"+nextDay+ " and I should add "+value+" days");

    nextDay.setDate(start.getDate()+parseInt(value)); // Strings are converted to integers here

    console.log("The next day is:"+nextDay);

});

The days are defined as strings and not numbers. If you change them to numbers it should work:

var days= [1, 3, 4];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM