Sometimes, we want to format date to MM/dd/yyyy in JavaScript.
In this article, we’ll look at how to format date to MM/dd/yyyy in JavaScript.
How to format date to MM/dd/yyyy in JavaScript?
To format date to MM/dd/yyyy in JavaScript, we can use some date and string methods.
For instance, we write
const getFormattedDate = (date) => {
let year = date.getFullYear();
let month = (1 + date.getMonth()).toString().padStart(2, "0");
let day = date.getDate().toString().padStart(2, "0");
return month + "/" + day + "/" + year;
};
to create the getFormattedDate
function.
In it, we get the 4 digit year from the date
with getFullYear
.
getMonth
gets the month.
getDate
gets the date of the month.
We call padStart
to prepend 0 to pad the string to 2 digits if the number has less than 2 digits.
And then we return the month
, day
and year
combined into a new string.
We add 1 to the month returned by getMonth
to make it a human readable month number.
Conclusion
To format date to MM/dd/yyyy in JavaScript, we can use some date and string methods.