ohadinho
ohadinho

Reputation: 7144

new Date(...) adds a month forward

I'm developing with node.js, and I'm trying to create a date object on the server.

when coding:

var birthyear = 2000;
var birthmonth = 7;
var birthday = 24;
var date = new Date(birthyear, birthmonth, birthday);
console.log(date);

OUTPUT:

Thu Aug 24 2000 00:00:00 GMT+0300 (Jerusalem Daylight Time)

As you can see, I'm getting August instead of July.

How can I fix that issue ?

Upvotes: 3

Views: 452

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206008

Months in JS start at 0 so it's a quite an easy fix:

var date = new Date(birthyear, birthmonth-1, birthday); 

DEMO

Upvotes: 2

waplet
waplet

Reputation: 151

Yea, that's weird, but months should be counted starting with

0

Upvotes: 0

Chris Hayes
Chris Hayes

Reputation: 12020

Months in the JavaScript Date() constructor are 0-indexed, meaning that month 7 actually is August. Use the value 6 for July.

Annoyingly enough, Date is rather inconsistent about which fields are 0-indexed and which are 1-indexed, and in fact the same field can be either one depending on the context. You should always refer to documentation when you have to use dates.

Upvotes: 1

hexacyanide
hexacyanide

Reputation: 91619

The month argument in the Date() constructor doesn't start at 1 for January, but instead at 0. Therefore, supplying the month value of 7 gives you the eight month, which is August.

From MDN:

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

Upvotes: 6

Related Questions