Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date Explanation

Tags:

javascript

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

like image 205
James King Avatar asked Dec 01 '25 04:12

James King


1 Answers

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);
like image 147
itsmejodie Avatar answered Dec 02 '25 18:12

itsmejodie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!