Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using 0 to identify the last day of a month doesn't work globally

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading