skip to Main Content

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

Answers


  1. Try this?

    lastDayDate.toISOString().split('T')[0]
    
    Login or Signup to reply.
  2. one way: const formattedDate = lastDayDate.toJSON().slice(0, 10);

    Login or Signup to reply.
  3. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search