How to sort next.js blog posts by date

Convert the date string to a date object

npm install Luxon
/components/postList/postList.jsimport { dateTime } from 'Luxon'
DateTime.fromFormat('09-06-2022, 'm-d-yyyy')

Order blog post by most recent date

/components/postLists/postLists.js
const
sortBlogPostsByDate = posts.sort((a, b) => {
const beforeDate = DateTime.fromFormat(a.frontmatter.date, 'm-d-yyyy')const afterDate = DateTime.fromFormat(b.frontmatter.date, 'm-d-yyyy')return afterDate - beforeDate})
return (<div className="postlist">{posts && sortBlogPostsByDate.map((post) => { return (   <DivList key={post.slug}>    <Link href={{ pathname: `/${post.slug}` }}>     <PostTitle href={`/${post.slug}`}>       {post.frontmatter.title}     </PostTitle>    </Link>    <PostData>

<PostTag>{post.frontmatter.tags}</PostTag>
<PostDate className="post-date"> {post.frontmatter.date} </PostDate> </PostData> <PostText>{post.frontmatter.description}</PostText> </DivList>

)
})} </div>)
https://www.agirl.codes/sort-nextjs-blog-posts-by-date

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store