Efrin
Efrin

Reputation: 2423

Javascript new Date() returns different date

I did create a date object out of '31/12/2018':

new Date('2018', '12', '31')

It does however create something completely different that I would expect.

Date {Thu Jan 31 2019 00:00:00 GMT+0100 (Central European Standard Time)}

What's happening?

Upvotes: 0

Views: 239

Answers (3)

Artyom Pranovich
Artyom Pranovich

Reputation: 6962

You've forget that months in JS starts with 0 instead 1.

Please use

new Date('2018', '11', '31')

in your case.

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128791

Months start with 0 in JavaScript. January is 0; December is 11. 12 represents January the following year. You'll want to use 11 instead of 12:

new Date('2018', '11', '31')
-> Mon Dec 31 2018 00:00:00 GMT+0100 (Central European Standard Time)

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382140

Months are indexed starting from 0. Use 11 for December, not 12 :

new Date(2018, 11, 31)

(and yes, there should be numbers instead of strings, which makes it a little less confusing)

From the MDN :

month

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

Upvotes: 3

Related Questions