mschadegg
mschadegg

Reputation: 799

Problems with Date() in JavaScript - it adds one month?

I have a strange problem with Date() in JavaScript.

I have the following simple code:

var date = new Date(2013, 11, 01, 00, 00, 0, 0);
alert(date);

That should set the Date to 01 November 2013 00:00:00:00 But instead it sets it to December? As you can see in this fiddle http://jsfiddle.net/CBqK2/

What is wrong?

Upvotes: 4

Views: 2861

Answers (4)

Strikers
Strikers

Reputation: 4776

the Date has the list of months weekdays starting from zero.

for months it is 0-11 for Jan to Dec and for Week days it is 0-6 for Sun - Sat.

when you say.

var date = new Date('1381751517000') // I have used the timestamp in milliseconds for 2013-10-14T11:51:00 as js accepts timestamp in milliseconds.

now if we say

day = date.getDay();

it return 1, i.e Monday,

month = date.getMonth()

it returns 9 i.e October.

in the same way when we create the date using the format ('YYYY,MM,DD,HH,mm,ss,ms') we should give the input also in the same way.

Upvotes: 0

Mumthezir VP
Mumthezir VP

Reputation: 6551

The Date() returns the month (from 0 to 11) for the specified date, according to local time.

eg:January is 0, February is 1, and so on.

if you want to start from 0 onwards use below format

var date = new Date('2013/10/01');

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

JavaScript months are 0 based, just to confuse you.

From MDN for the Date constructor:

month Integer value representing the month, beginning with 0 for January to 11 for December.

So for your example:

var date = new Date(2013, 10, 01, 0, 0, 0, 0);
alert(date);

You can read more about Date on MDN here.

Upvotes: 18

Igl3
Igl3

Reputation: 5108

Set the second value to 10. Date class begins with a 0 for January like in an Array ;)

Upvotes: 3

Related Questions