Today, we aim to clearify the way to format Date object in javascript.
There are frustratingly many ways to format Date in javascript.
Let's say you want to display 'published at' in your blog. If you are using database, you retrieve data like created_at of your blog which is in the form like '2024-02-18T03:01:16Z' (say).
mm,dd,yyyy
The following article was very helpful.
Borislav Hadzhiev
https://bobbyhadz.com/blog/javascript-format-date-dd-mm-yyyy
In this article, he introduced the following functions,
function padTo2Digits(num: any) {
return num.toString().padStart(2, '0');
}
function formatDate(date: any) {
return [
[Intl.DateTimeFormat('en', { month: 'long' }).format(date.getMonth() + 1),
padTo2Digits(date.getDate())].join(' '),
date.getFullYear(),
].join(', ');
}
Using the functions above we format our data. But first we have to convert our data 2024-02-18T03:01:16Z to data object. Since I'm using sanity to write a blog, I use GROQ to retrieve data. If you are not using sanity, you can skip reading getData function and think of data._createdAt as 2024-02-18T03:01:16Z in the following code.
async function getData(slug: string) {
const query = `
*[_type=="blog" && slug.current == "${slug}"] {
"currentSlug":slug.current,
title,
content,
titleImage,
_createdAt,
_updatedAt,
}[0]`
const data = await client.fetch(query);
return data
}
export default async function BlogArticle({params}: {params:{slug: string}}) {
const data: fullBlog = await getData(params.slug);
const createdAtDataObject = new Date(data._createdAt)
const createdAtDate = formatDate(createdAtDataObject);
return (
...
)
}
With this, createdAtDate must be in the form of 2/18/2024.
Name of month, dd, yyyy
Let's take a step forward and change the format a little bit to make it more neat. Here we want February, 18. 2024.
This is fairly easy. You just need to make a function that converts a number to name of the month and use it in formatDate function.
function numberToMonth(number: number) {
const months = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
};
return months[number] || "Invalid month number";
}
function padTo2Digits(num: any) {
return num.toString().padStart(2, '0');
}
function formatDate(date: any) {
return [
[numberToMonth(date.getMonth() + 1),
padTo2Digits(date.getDate())].join(' '),
date.getFullYear(),
].join(', ');
}
Conclusion
We discussed how to format date object in javascript.
As of Feb 2024, there is no built-in functions to achieve what we did today. Hope this article helped reduce the pain in dealing with date object in javascript.
Happy coding!