0

When I create the following date variable:

    var d = new Date('2018-01-01')

and run

    d.getDate()

I get 31. when I run

d.getMonth()

I get 11.

Why do I get 31 and 11 rather than 1 and 1?

Chip
  • 125
  • 1
  • 9
  • Please change your title to ask a question or describe your problem. – takendarkk Sep 27 '18 at 23:01
  • 1
    Because the months are zero count `0-11`. – zer00ne Sep 27 '18 at 23:04
  • So then why don't I get 0 for 1? Why does it go to 11? – Chip Sep 27 '18 at 23:05
  • Also note the use of [date strings are discouraged for the Date constructor due to differences in browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters) – Patrick Evans Sep 27 '18 at 23:06
  • Check this: https://stackoverflow.com/questions/2488313/javascripts-getdate-returns-wrong-date – protoproto Sep 27 '18 at 23:07
  • In that post, the output seems to be one number off. I'm not sure why I'm getting 31, 11 rather than 1, 0. – Chip Sep 27 '18 at 23:09
  • 2
    The short answer is that ISO 8601 format dates are treated as UTC. If your timezone is west of Greenwich, the local date becomes 2017-12-31 (and months are zero indexed hence *getMonth* returns 11). – RobG Sep 27 '18 at 23:10

2 Answers2

1

If you live in the western hemisphere, this is a timezone issue, I believe.

Javascript timers are based on Unix ticks(basically seconds since January 1, 1970). Since date-only format strings using ISO 8601 are treated as UTC, Javascript mitigates it by adding your local timezone, thus adjusting your time.

Example: 2018-01-01 00:00:00 - your timezone = 2017-12-31 {your timezone offset}.

You can recreate this by moving your timezone to negative UTC, try creating a date using the new Date('string') method, then getting the date.

You can fix this by using the new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]); method instead.

Here's a better understanding to it.

Nathan
  • 1,520
  • 1
  • 12
  • 21
  • I've found that date.getUTCDate() will do what is expected here. `date.getDate('2023-02-01') = 31` BUT `date.getUTCDate('2023-02-01') = 01` – Ahmad Shah Feb 08 '23 at 15:50
0

The months are 0 indexed, meaning they start from 0 and go up to 11.

Paul McLoughlin
  • 2,279
  • 2
  • 18
  • 24