4

This javascript method for determining the last day of the month doesn't work for me, who is in Ukraine, but it works for my colleague in the US. I get 2022-10-30 and my colleague gets 2022-10-31. What is the problem?

var now = new Date();

const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString().split('T')[0];

console.log(lastDayOfMonth)

I created a codepen and we got different results:

Сodepen to check

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Andy Kotov
  • 43
  • 5
  • Replace `.toISOString().split('T')[0];` with `.toLocaleDateString('en-CA')` to get the local date, not UTC date (you can also use language 'sv'). :-) Also see [*Format JavaScript date as yyyy-mm-dd*](https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?r=SearchResults&s=2%7C870.1060). – RobG Oct 27 '22 at 12:01

1 Answers1

4

It's because of timezones. new Date works in local time, but toISOString formats the UTC version of the date/time. You don't want to mix UTC methods and local methods, because you'll get inconsistent results. In this case, since you're ahead of UTC, your local date/time at midnight is on the previous day in UTC. But in the States, they're behind UTC (and not so far behind they have the opposite problem), so it works for them.

Start with midnight UTC instead, via the UTC method, so you're consistently using a single timezone:

const now = new Date();
const lastDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth() + 1, 0))
    .toISOString()
    .split("T")[0];
console.log(lastDayOfMonth);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • The real issue is that the OP is using an inappropriate method to format the date. Going via *Date.UTC* fixes that, but the *Date* produced is not "local" any more. – RobG Oct 28 '22 at 02:31
  • @RobG - I think the *real* issue is mixing UTC and local. Since the OP's not storing the date, it doesn't matter whether you're consistently using UTC or consistently using local, you just have to not mix them. But I like the UTC solution because the result of `toISOString` doesn't vary by locale, and the same code can be used regardless of the timezone of the person running it. – T.J. Crowder Oct 28 '22 at 07:53