I have a date as a string like so: "2021-08-12". But, I want to display it nicely on the frontend like this : 11th August, 2021
Any recommendations on how to approach this?
I have a date as a string like so: "2021-08-12". But, I want to display it nicely on the frontend like this : 11th August, 2021
Any recommendations on how to approach this?
Use a library like Moment.js
moment().format("Do MMMM, YYYY");
Do
Day of Month 1st 2nd ... 30th 31stMMMM
Month January February ... November DecemberYYYY
YearSee also How to format a JavaScript date?
If 12th vs 11th was not a typo and you actually want to subtract a day from the date,
moment().subtract(1, 'day')
before you display it as above.
You can do this with vanilla JavaScript as following. See the documentation for Date.toLocaleString()
.
const dateString = "2012-01-01";
function formatDate(dateString) {
const suffix = ["st", "nd", "rd", "th"];
const date = new Date(dateString + " 0:0:0");
dateString = date.toLocaleString("en-US", {
month: "long",
year: "numeric",
});
const day = date.getDate();
return `${day}${suffix[day < 4 ? day - 1 : 3]} ${dateString}`;
}
console.log(formatDate(dateString));
One little advice, build the habit of quickly looking up documentation instead of asking help on SO. I'm giving you this answer from the MDN docs. You can also try using devdocs.io
with their offline web app to quickly lookup docs.
Convert it to Date object and from there create whatever format you want:
const myDate = "2021-08-21";
const date = new Date(myDate + " 0:0:0");
console.log(date.getDate() + "th " + date.toLocaleDateString("en-us", {month: "long"}) + ", " + date.getFullYear());