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 ?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With