John
John

Reputation: 11

How does the Date.getDate() function work?

I'm planning to write a couple of date util functions for my project, but cannot understand why Date.prototype.getDate is returning weird numbers. For example:

I ran the following code:

alert(new Date(2019, 04, 00).getDate());

In my head I was expecting to receive 31 (the number of days of May), but received 30!

The same happened with the following snippet:

alert(new Date('2019-04-01').getDate());

In this case, I was expecting to receive 1 because according to the documentation I found in MDN:

The getDate() method returns the day of the month for the specified date according to local time.

But instead received 31!

And finally, when ran:

alert(new Date('2019-04-02').getDate());

I was expecting to see 2, but saw 1! (which has nothing to do with the previous logic!)

What am I doing wrong?

Upvotes: 1

Views: 685

Answers (3)

RobG
RobG

Reputation: 147553

The code:

new Date(2019, 04, 00)

will produce a date for the zeroth day of May, 2019 which is interpreted as the last day of April, which is the 30th, so:

new Date(2019, 04, 00).getDate()

returns 30.

In:

new Date('2019-04-01')

the string is (illogically) parsed as UTC. The getDate method uses the host timezone setting to determine the local date, so:

new Date('2019-04-01').getDate()

might return 1 (April) or 31 (March) depending on whether the host timezone offset is positive or negative respectively.

E.g. for a user at UTC +0530 the local date will be 2019-04-01 05:30:00, but for a user at UTC -0400 the local date will be 2019-03-31 20:00:00.

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44145

For the first case, you're getting 30 because you're checking the number of days in the 4th month - April. May is the 5th month. Here's a demo - with February as the 2nd month as well:

console.log(new Date(2019, 04, 00).getDate());
console.log(new Date(2019, 05, 00).getDate());
console.log(new Date(2019, 02, 00).getDate());

The second case does actually produce 1:

console.log(new Date('2019-04-01').getDate());

And the third case does actually produce 2:

console.log(new Date('2019-04-02').getDate());

Upvotes: 0

Pointy
Pointy

Reputation: 414086

The Date methods "fix" weird non-real dates. If you set the date (day-of-month) to zero, you get the last day of the previous month. All of the setter methods behave similarly.

Note also that months are numbered from zero: January is 0, not 1.

Upvotes: 1

Related Questions