Reputation: 799
I have a weird bug regarding javascript date object
I have something like
var year = 2014;
var month = 11;
var day = 29
var date = new Date(year, month , day);
console.log(date) -> give me Mon Dec 29 2014 00:00:00 GMT-0800 (PST)
var monthNum = date.getMonth();
console.log(monthNum) -> give me 11
If I change month to 12
, it gave me Thu Jan 29 2015 00:00:00 GMT-0800 (PST)
I am not sure why the month is off by one. Can someone help me out about this? Thanks!
Upvotes: 1
Views: 52
Reputation: 2510
Change the following line:
var date = new Date(year, month , day);
to:
var date = new Date(year, month - 1, day);
This is because months in the JS date constructor begin at zero, i.e. 0 = Jan, 1 = Feb, ...
Upvotes: 1
Reputation: 1263
Months in JavaScript date objects starts at 0. That means January is 0 while December is 11.
Upvotes: 4
Reputation: 190945
The months argument in that constructor are 0-based, not 1-based.
Upvotes: 3