James King
James King

Reputation: 1614

Javascript Date Explanation

The following code:

//var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var today = new Date(2013,0,31); 
var tomorrow = new Date(); 
tomorrow.setDate(today.getDate() + 1);
alert("New date is "+tomorrow.getFullYear() +", "+ tomorrow.getMonth()+", "+ tomorrow.getDate())

...outputs: 2014, 1, 1

(Demo: http://jsfiddle.net/3pA3Q/5/)

Can anyone explain this?

Also, these two have the same result:

var today = new Date(2013,11,31); 
var today = new Date(2013,12,31); 

I understand "month beginning with 0 for January to 11 for December", so new Date(2013,12,31) should be Year 2014, January, 31st

Upvotes: 3

Views: 107

Answers (1)

itsmejodie
itsmejodie

Reputation: 4228

You initialised tomorrow to be todays date, so in this line tomorrow.setDate(today.getDate() + 1); you're simply adding 1 day to todays date.

You would be better off cloning your date:

var today = new Date(2013,0,31); 
var tomorrow = new Date(today.getTime()); // Get a copy
tomorrow.setDate(tomorrow.getDate() + 1);

Upvotes: 3

Related Questions