I have this kind of code where I only get month and year
dates are coming as : "6 2023"
let checkCurrentDate = new Date().getMonth() + 1 + ' ' + new Date().getFullYear();
console.log(checkCurrentDate);
I want the date to be in mm/dd/yyyy
format. Also, in some cases, dates are coming as "June 2023"
and I need the date in the same mm/dd/yyyy
format. Please guide what I am missing here .
The dd should be the first of every month .
2
Answers
There are two ways to format a date a string in English US format.
Intl.DateTimeFormat
toLocaleDateString
If you want padding, you need to specify
2-digit
as an option for month and day.Note: Don’t forget the year!
Now, to put it all together:
Output
Here is a better version that is more efficient at parsing the month name. All the months for the
en-US
are generated ahead of time.I’d suggest checking the documentation first before asking a question here.
I understand that working with dates might be tricky, but all your answers could be found here
Alternatively, you could use packages like moment or dayjs