Jack
Jack

Reputation: 9784

Javascript for loop behaviour outputting the same result each iteration

I'll admit I'm a bit of a JS novice, and coming from a PHP background, my idea of scope is clearly different to Javascript's.

// There's a date set, so begin processing
var original_date       = new Date($('input#tour_encoded_dates').val());
var date_search_string  = ''; 
var day_limit           = 14;
var timestamp           = '';

// Go forwards day_limit days
for(var i = 0; i < day_limit; i++) {
    timestamp = strtotime('+'+i+' days', original_date);
    calculated_date = new Date(timestamp).format('Y-m-d');
    date_search_string += calculated_date + ' ';
}

console.log(date_search_string);

The output from console.log() is:

2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10 2013-10-10

I would have expected each iteration to increase the date by one day, but they remain the same.

For reference, if I change the final line of the loop to date_search_string += timestamp + ' '; the output is as follows:

1381363200000 1381363286400 1381363372800 1381363459200 1381363545600 1381363632000 1381363718400 1381363804800 1381363891200 1381363977600 1381364064000 1381364150400 1381364236800 1381364323200

So the issue is clearly with the calculated_date variable - right?

Can someone explain the proper way to do this? Thanks.

Upvotes: 0

Views: 132

Answers (1)

user180100
user180100

Reputation:

There is 86400 (i.e. 1/1000 day), between each timestamp.

You are computing (in strtotime) as if timestamps were seconds but they are milliseconds.

Upvotes: 2

Related Questions