Gecko
Gecko

Reputation: 21

Date.getDate always return 1

For an unknown reason, getDate always return 1 instead of 28. I'm using NodeJS 10.6.0 and Typescript 3.2.2.

const lastDay = new Date();
lastDay.setDate(0);
lastDay.setHours(24, 59, 59, 999);
console.log(lastDay, "|", lastDay.getDate()); // 2019-02-28T23:59:59.999Z | 1

Edit: I'm trying to get the last day of the previous month at the last ms. Then setDate(0) is correct. What i don't understand exactly is, why when i print the time i get 28T23:59:59.999Z and getDate() returns the next day.

Edit2: Effectively using getUTCDate fix my issue, it remain weird to me due to the strange way it's implemented. IMO each methods should be more explicitely named to avoid this kind of issue.

Upvotes: 1

Views: 993

Answers (4)

Fakhar Ahmad Rasul
Fakhar Ahmad Rasul

Reputation: 1691

thats happening because you are setting the hours as well, remove the line of code where you are setting the hours and you will get the expected result:-

const lastDay = new Date();
lastDay.setDate(0);
//lastDay.setHours(24, 59, 59, 999);
console.log(lastDay, "|", lastDay.getDate()); //Thu Feb 28 2019 19:01:20 GMT+0500 (Pakistan Standard Time) "|" 28

Upvotes: 0

Shriekin Ninja
Shriekin Ninja

Reputation: 96

It's doing its job as advertised.

lastDay.setDate(0);

set the day to the last of the relative month. then you add a full day with 24+ so it's the first day of the next month.

Upvotes: 1

Pointy
Pointy

Reputation: 413717

When you set the hours, you're passing 24 instead of 23.

Also, when you print the date, you might want to use .toLocaleString() so that you get the local time instead of UTC.

Upvotes: 1

ttulka
ttulka

Reputation: 10882

It's actually correct:

Date.prototype.getDate()

Returns the day of the month (1-31) for the specified date according to local time.

You can test it so:

const lastDay: Date = new Date();
lastDay.setDate(3);
lastDay.setHours(24, 59, 59, 999);
console.log(lastDay, "|", lastDay.getDate()); // 2019-03-03T23:59:59.999Z | 4

Upvotes: 1

Related Questions