formatDate

A lightweight utility function to format JavaScript dates into customizable string formats. It supports multiple date formats, month names, and day names for diverse display needs.
> function formatDate(
        date: Date | string | null = new Date(),
        options?: {
            format?: DateFormat;
            monthFormat?: "short" | "long";
            dayFormat?: "short" | "long";
        }
 ): string;
Parameters
  • date: The date to format. Defaults to the current date. Accepts a Date object, a string in `YYYY-MM-DD` format, or null.
  • Returns: A formatted string representing the date in the specified format.

Supported Formats

FormatExample OutputDescription
YYYY-MM-DD2024-11-04ISO-style format.
DD-MM-YYYY04-11-2024Day-first numeric format.
MM-DD-YYYY11-04-2024US numeric format.
YYYY/MM/DD2024/11/04ISO with slashes.
DD/MM/YYYY04/11/2024Day-first with slashes.
Month DD, YYYYNov 04, 2024Full month name first.
DD Month YYYY04 Nov 2024Day with full month.
YYYY2024Year only.
MM11Padded numeric month.
mm11Unpadded numeric month.
MNovShort month name.
DD04Padded day.
dd4Unpadded day.
DMonShort day name.

If an unsupported format string is provided, an error will be thrown with a message indicating the unsupported format.

Example

import { formatDate } from "@explita/daily-toolset";

const date = new Date("2024-01-01");

// Using default format
console.log(formatDate(date));
// Output: "01/01/2024" (default: DD/MM/YYYY)

console.log(formatDate(date, { format: "YYYY-MM-DD" }));
// Output: "2024-01-01"

console.log(formatDate(date, { format: "Month DD, YYYY" }));
// Output: "Jan 01, 2024"

console.log(formatDate(date, { format: "D", dayFormat: "long" }));
// Output: "Monday"

console.log(formatDate(date, { format: "M", monthFormat: "long" }));
// Output: "January"

console.log(formatDate("invalid-date-string"));
// Throws Error: Invalid date string provided: "invalid-date-string".