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:
CodePudding user response:
It's because of timezones. new Date
works in local time, but toISOString
formats the UTC version of the date/time. 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:
const now = new Date();
const lastDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth() 1, 0))
.toISOString()
.split("T")[0];
console.log(lastDayOfMonth);