DEV Community

JAKER HOSSAIN
JAKER HOSSAIN

Posted on

1 1 1 2 2

JavaScript Date Utility: Convert, Format & Display Dates

The getFormattedDate utility function simplifies date formatting in JavaScript and TypeScript applications. It ensures reliable date conversion while offering multiple format options, including dd/MM/yyyy, MM/dd/yyyy, yyyy/MM/dd, and yyyy/dd/MM. Additionally, it supports a full date style that displays the month name for improved readability (e.g., "15 October 2024").

import { allMonths } from "@/constants/months.constants";

export const getFormattedDate = (
  date: string | Date,
  format?: "dd/MM/yyyy" | "MM/dd/yyyy" | "yyyy/MM/dd" | "yyyy/dd/MM",
  fullDate: boolean = false
): string => {
  // <= Ensure the input is a Date object =>
  const dateObj = typeof date === "string" ? new Date(date) : date;

  if (isNaN(dateObj.getTime())) {
    throw new Error("Invalid date");
  }

  const day = dateObj.getDate().toString().padStart(2, "0");
  const month = (dateObj.getMonth() + 1).toString().padStart(2, "0");
  const year = dateObj.getFullYear();

  // <= handle full date style =>
  if (fullDate) {
    return `${day} ${allMonths[dateObj.getMonth()]} ${year}`;
  }

  // <= Handle custom format =>
  switch (format) {
    case "dd/MM/yyyy":
      return `${day}/${month}/${year}`;
    case "MM/dd/yyyy":
      return `${month}/${day}/${year}`;
    case "yyyy/MM/dd":
      return `${year}/${month}/${day}`;
    case "yyyy/dd/MM":
      return `${year}/${day}/${month}`;
    default:
      throw new Error("Unsupported format");
  }
};

<== Use case ==>
const exampleDate = "2024-02-10T12:30:00Z"
getFormattedDate(exampleDate, "dd/MM/yyyy")

# To get full date, you can use fullDate true.

Enter fullscreen mode Exit fullscreen mode

*Key Features:
*
✅ Flexible Formatting Options – Supports various date formats to match different regional preferences.
✅ Enhanced Readability – The fullDate option provides a user-friendly date format with the month's full name.
✅ Reliable Date Conversion – Ensures that string inputs are properly converted into valid Date objects.
✅ Error Handling – Prevents issues with invalid dates by throwing an explicit error message.
✅ SEO & UX Improvement – Well-formatted dates enhance user experience and improve content readability, which is crucial for SEO.

Perfect for use in e-commerce platforms, booking systems, blogs, and dashboards, this utility optimizes date display while keeping code clean and efficient. 🚀

All credit goes to SHARIFUL ISLAM and thanks for making it, it's amazing and enhances code readability.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs