JavaScript convert date format to "YYYY-MM-DD"

5.2k Views Asked by At

I have a JavaScript string date:

js code:

const lastDayDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 0);
const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
const formattedDate = lastDayDate.toLocaleDateString('se-SE', options);

The output of console.log(formattedDate) is something like:

05/31/2023

My question is how to convert it to :

2023-05-31

Any friend can help ?

3

There are 3 best solutions below

2
AudioBubble On BEST ANSWER

Try this?

lastDayDate.toISOString().split('T')[0]
1
Mark Schultheiss On

one way: const formattedDate = lastDayDate.toJSON().slice(0, 10);

2
Jordy On

Be careful, lastDayDate.toISOString().split('T')[0] will return UTC Date instead of Local Date. So the correct way to handle this is with formatDate function which gets a local date as year, month, and day.

let formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const localDate = `${year}-${month}-${day}`;
  return localDate;
};

const lastDayDate = new Date(2023, 4 + 1, 0);
console.log(lastDayDate);
const formattedDate = formatDate(lastDayDate);
console.log(formattedDate);