Formatting Date in JS


Updated Aug 26th, 2021

Not creating my onw, in this getting form an API and it looks like this:


So I can put in the format of Aug 23, 2021?

Above your map function create a new date object and pass it the date received from the API. Then create a formatted date constant. Pass this constant variable in your map function.

          { => {
            const dateOfPost = new Date(post.modified)
            const formattedDate = `${dateOfPost.toLocaleString("default", { month: "short" })} ${dateOfPost.getDate()}, ${dateOfPost.getFullYear()}`

            return (
              <a key={post.title} href="#">

Article one here.

And example of using a package:

The next-wordpress-starter leverages the “date-fns” package to “add a formatted date to the post list and page”

// in the src/lib/datetime.js file

import { format } from 'date-fns';

/* formatDate

export function formatDate(date, pattern = 'PPP') {
  return format(new Date(date), pattern);

/* sortObjectsByDate

export function sortObjectsByDate(array, { key = 'date' } = {}) {
  return array.sort((a, b) => new Date(b[key]) - new Date(a[key]));