Reputation: 218
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
Upvotes: 1
Views: 1850
Reputation: 1554
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);
});
Upvotes: 2
Reputation: 5781
The days are defined as strings and not numbers. If you change them to numbers it should work:
var days= [1, 3, 4];
Upvotes: 1