How to Format WordPress API Date and Time

wordpress logo

If you are using WordPress .com’s REST API, the date returned from a blog post is in ISO format. Here is what I did to change the ISO formatted date into something more readable for my blog.

const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ];  

const newDate = new Date("2019-06-25T05:30:50+00:00");
const year = newDate.getFullYear();
const month = newDate.getMonth() + 1;
const day = newDate.getDate();
const renderedDate = `${months[month - 1]} ${day}, ${year}`;

First, I created an array with all of the months since the getMonth() method returns a number that I need converted to the name of a month. The newDate variable creates a new date object with a specified date and time that was returned from the WP REST API. The year variable gets the full year from the newDate varible, so does the month and the day. I used a template literal to format the finalized rendered output to include in my React component. Here is the final output:

This image has an empty alt attribute; its file name is date.png

Leave a comment

Your email address will not be published. Required fields are marked *