Nikhil Khurana
Nikhil Khurana

Reputation: 422

Month gets updated on adding minutes to Javascript Date Object

I'm adding Time in Javascript Date object and month gets increased by 1. Any idea what exactly is wrong in the logic. enter image description here

var add_minutes =  function (dt, minutes) {
    return new Date(dt.getTime() + minutes*60000);
}
console.log(add_minutes(new Date(2014,10,2), 30).toString());

CodePen Link

Upvotes: 0

Views: 52

Answers (3)

Rahul Sharma
Rahul Sharma

Reputation: 5995

It's because month is zero-indexed. Try logging new Date(2014,10,2).toString(). 10 means November.

Upvotes: 1

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

Everything is OK. The thing is, that in Date() the months are counted from 0, so 10 is not October, it's November. See this

Upvotes: 1

Kei
Kei

Reputation: 1026

The month parameter is zero-indexed. Thus, new Date(2014,0,1) is January 1, and new Date(2014,11,1) is December 1.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Specifically,

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

Also note that Date.getMonth() returns a zero-indexed month while Date.getDate() returns the day of the month as-is.

var date = new Date(2014, 0, 10);

console.log("Date:" + date.toLocaleString("en-US"));
console.log("getMonth(): " + date.getMonth());
console.log("getDate(): " + date.getDate());

Upvotes: 1

Related Questions