I have a date:
console.log(lastDayDate)
Output:
Sun Apr 30 2023 00:00:00 GMT-0500 (Central Daylight Time)
Then I use:
formattedDate = lastDayDate.toLocaleString().split(',')[0];
console.log(formattedDate)
Output is:
4/30/2023
How can I change it to :
04/30/2023
4
Answers
you could fix it with
`let lastDayDate = new Date("Sun Apr 30 2023 00:00:00 GMT-0500 (Central Daylight Time)");
let day = String(lastDayDate.getDate()).padStart(2, ‘0’);
let month = String(lastDayDate.getMonth() + 1).padStart(2, ‘0’); // Se suma 1 porque getMonth() devuelve el mes de 0 (enero) a 11 (diciembre)
let year = lastDayDate.getFullYear();
let formattedDate =
${month}/${day}/${year}
;console.log(formattedDate); // Debería imprimir: 04/30/2023`
You can split the
4/30/2023
bit with/
and check whether the date/month is less than 10. Created a function for that (also checks the date):🙂
You can use
Date#toLocaleDateString
with additional options.Since you are using JavaScript, there are a lot of awesome 3’rd party libraries out there that can help you play around date object. The most advisable 2 are momentjs and date-fns.
Creating a moment instance of a js Date() object is quite easy,
moment.js also has a crazy amount of formats available, for all other requirements.