Formatting the date
Last updated
Last updated
When you view a post you may notice that the date is not formatted in an easy to read way.
Let's fix that now. Doing this gives us the opportunity to use an external library with Frontity. Installing and using external JavaScript libraries is something that you're likely to need to do in real-world project development, so it's well worth covering here.
Frontity will happily work with almost any package available on . There are a number of packages for formatting dates, probably the best known of which is . However, Moment is a large package so in the interests of streamlining our project as much as possible we're instead going to use the more lightweight to format our date string.
Open your terminal and ensure that you're in the root directory of your project. You can then install Day.js by running the following command:
If you check the package.json
file in the root of your project directory you will now see that dayjs
has been added as a dependency.
Next, since the <Post>
component is the only one that's going to use it, let's import Day.js into our post.js
file:
We now need to create a Day.js object and we pass in post.date
, which is the tricky to read date string that is currently displaying in our post. We can do that with dayjs(post.date)
, and we then call the format
function of the dayjs
object passing it a formatting string.
We'll store the result in a variable (which we'll call formattedDate
) for later use.
Finally we'll use the formattedDate
variable holding our formatted date in our component by replacing post.date
with it.
Your post.js
file should now look like this:
Our date is now formatted in a much more pleasing way.
If, like us, you prefer to keep your bundle sizes as small as possible is a great resource for finding alternatives to large and heavyweight npm packages.
See the for other possible formatting strings. For example, try replacing DD MMMM YYYY
above with MMM DD, YYYY
or DD-MM-YY
to see how the appearance of the date changes. Use whichever version of the formatted date that you prefer.
Check you're on the right track by comparing your changes with .