DEV Community

TechSynthesis
TechSynthesis

Posted on

Format date in JS/React without any Library.

This is a simple utility function that I wrote for my Ecommerce Dashboard it takes the unformatted standard ISO 8601 date time string and formats it into a more readable format.

Something like this
readable date format

So lets get started.
Create a new .js file calledgetDateHandler.js

export default function getDateHandler(date) {
    const months = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
    ];
    const newDate = new Date(date);
    const getMonth = months[newDate.getMonth()];

    let time;
    if (newDate.getDate() === new Date().getDate()) {
        time = `${newDate.getHours()}:${newDate.getMinutes()}`;
    }
//What this does is if the current date matches the date entered it displays the time else it displays the date
    const fomattedDate = time
        ? ` Today at ${time}`
        : `${getMonth} ${newDate.getDate()}, ${newDate.getFullYear()}`;

    return fomattedDate;
}
Enter fullscreen mode Exit fullscreen mode

Using the above function is simple. Import it into wherever you need to use it. In my case within a order map function in react. wrap the function around the date that requires formatting. getDateHandler("2021-11-04T08:37:13.099+00:00")

Below you can see a demo of how it works.

import React from "react";
import getDateHandler from "../utils/getDateHandler";

export default function UsingDateFormatScreen(props) {
    const createdAt="2021-11-04T08:37:13.099+00:00";
    return (
    <div>
      <h1>Example Date : <br /> {getDateHandler(createdAt)} </h1>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Do let me know if you found this useful :)

Top comments (0)