Home > Software engineering >  Javascript Date Object returning incorrect first day of the month
Javascript Date Object returning incorrect first day of the month

Time:04-01

I'm using the following code in a React app to get the first day of the month (to set defaults for a date picker component).

let date = new Date();
let firstDay = new Date(date.getFullYear(), date.getMonth(), 1).toISOString().slice(0, 10);

For some reason today, on 1st April, it's returning 31st March. I've tested in Chrome console and various other online JS runtime tools and some return 31-03-2022 and some return 01-04-2022. Is there something I'm missing?

CodePudding user response:

As robertklep stated, timezone plays a large roll in dates.

The problem with your result is being masked by the fact you are slicing the date part of the ISOString. You'll likely see the full string as:

"2022-03-31T23:00:00.000Z".

Notice the time is 1 hour earlier than local time? This is in line with UTC. and is due to my current timezone that is offset by 1 hour.

If you're not concerned about timezone, simply use: .toLocaleDateString();

let date = new Date();
let firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
console.log("ISO-8601", firstDay.toISOString());
console.log("Local String:", firstDay.toLocaleDateString("en-GB"));

you can also use .toLocaleDateString("en-US") depending on format

CodePudding user response:

Try this:

let date = new Date();
let firstDay = date.getDate()   '-'
   (date.getMonth()  1)   '-'   date.getFullYear();

or this, if You want to have the result format with '0':

let date = new Date();
let firstDay = String(date.getDate()).padStart(2, '0')   '-'
   String(date.getMonth()  1).padStart(2, '0')   '-'   date.getFullYear();
  • Related