Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript convert date format to "YYYY-MM-DD" [duplicate]

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 ?

like image 247
William Avatar asked Feb 11 '26 12:02

William


2 Answers

Try this?

lastDayDate.toISOString().split('T')[0]

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);
like image 29
Jordy Avatar answered Feb 13 '26 18:02

Jordy