1

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 ?

William
  • 3,724
  • 9
  • 43
  • 76

3 Answers3

1

Try this?

lastDayDate.toISOString().split('T')[0]
  • Hi friend can you help me with this question https://stackoverflow.com/questions/76056658/javascript-const-txt-change-to-new-line-not-work – William Apr 19 '23 at 16:06
  • It got closed for already having answers. Just use: const obj = {"name":"John", "age":30, "city":"New York\n", "home":"yes"} No need for JSON.parse and newline is "\n" not forward slash. –  Apr 19 '23 at 16:11
1

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

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • Hi friend can you help me with this question https://stackoverflow.com/questions/76056658/javascript-const-txt-change-to-new-line-not-work – William Apr 19 '23 at 16:06
1

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);
Jordy
  • 1,802
  • 2
  • 6
  • 25
  • Hi friend can you help me with this question https://stackoverflow.com/questions/76056658/javascript-const-txt-change-to-new-line-not-work – William Apr 19 '23 at 16:06
  • Hi friend can you help with this question ? https://stackoverflow.com/questions/76094451/javascript-convert-api-to-object-and-create-another-value-to-hold-its-value – William Apr 24 '23 at 17:19