Blog - Next.js - Chapter #7 - Dates

In this chapter I add the date for each single post in list of posts as well as in every single post page after the title.

7.1 Date Component

I want to ceate a Date Component to show for each post the date. Keep following tutorial indications in Polishing the Post Page - Formatting the Date I install date-fns library in order to format the date:

node ➜ /workspaces/misenplace.node-main/blog (dev-chapter-7) $ yarn add date-fns

I create Date Component in blog/components/Date.tsx:

// blog/components/Date.tsx

import { parseISO, format } from 'date-fns';

export default function Date({ dateString }: any) {
  const date = parseISO(dateString);
  return (
    <ul className="posted-on">
        <time className="entry-date published" dateTime={dateString}>
          {format(date, 'LLLL d, yyyy')}

I want to add the post date for each post in list of posts:

// blog/components/Posts.tsx

import Link from 'next/link';
import Date from '../components/Date';

export default function Posts({ posts }: any) {
  return (
      { any) => {
        return (
 && (
            <li key={}>
              <h2 className="h4">
                <Link href={`/posts/${}`}>
              <Date dateString={} />

To show the date in single post page, I update blog/pages/posts/[id].tsx:

// blog/pages/posts/[id].tsx

import Layout from '../../components/Layout';
import MetaData from '../../components/MetaData';
import Link from 'next/link';
import Date from '../../components/Date';
import { getAllPostIds, getPostData } from '../../lib/posts';
import { newLinesIntoParagraphs } from '../../lib/functions';

export default function Post({ postData }: any) {
  return (
        <MetaData title={postData.title} description={postData.excerpt} />
        {postData.repository && (
            <span style={{ fontSize: '0.7em' }}>Repository: </span>
            <Link href={postData.repository}>
                rel="noopener noreferrer"
                style={{ fontSize: '0.7em', textDecoration: 'none' }}
        <div className="entry-meta">
          <Date dateString={} />
        <div className="excerpt">
        <div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />

/* Keep the existing code here */

Reference links

External links

  • date-fns - Modern JavaScript date utility library.
Back to home