74

I am trying to create a new date in javascript.

I have year, month and day. Following this tutorial, syntax for creating new date should be:

new Date(year, month, day, hours, minutes, seconds, milliseconds)

and that is exactly what I am doing:

var d = new Date(2016, 12, 17, 0, 0, 0, 0);

This should be december 17th 2016, but in my console output I see:

Tue Jan 17 2017 00:00:00 GMT+0100 (Central Europe Standard Time)

What am I doing wrong?

FrenkyB
  • 5,826
  • 13
  • 61
  • 102
  • 8
    Months start from 0. You should use this: var d = new Date(2016, 11, 17); – Antonio Dec 05 '16 at 19:40
  • 2
    In Javascript Date Object, months are 0 based. So 0 means January, 11 means December. try `var d = new Date(2016, 11, 17, 0, 0, 0, 0);` It should be fine. – Hiren Dec 05 '16 at 19:42

2 Answers2

87

January is month 0. December is month 11. So this should work:

var d = new Date(2016, 11, 17, 0, 0, 0, 0);

Also, you can just simply do:

var d = new Date(2016, 11, 17);
Drew13
  • 1,261
  • 3
  • 25
  • 46
Dean coakley
  • 1,473
  • 1
  • 9
  • 24
  • 1
    why the month is 0 based & year,day not – CMS Dec 24 '19 at 06:05
  • 2
    Seems it's just an old tradition that javascript copied from POSIX/Java. https://linux.die.net/man/3/localtime , http://web.mit.edu/java_v1.0.2/www/javadoc/java.util.Date.html#getMonth%28%29 – Dean coakley Dec 28 '19 at 00:54
  • so confusing, I was wondering my weekOfYear() function returned 5 for January 1st – nipunasudha Nov 27 '20 at 02:20
53

According to MDN - Date:

month

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

You should subtract 1 from your month:

const d = new Date(2016, 11, 17, 0, 0, 0, 0);
Elias Soares
  • 8,741
  • 4
  • 26
  • 54