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;
- 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
Format | Example Output | Description |
---|---|---|
YYYY-MM-DD | 2024-11-04 | ISO-style format. |
DD-MM-YYYY | 04-11-2024 | Day-first numeric format. |
MM-DD-YYYY | 11-04-2024 | US numeric format. |
YYYY/MM/DD | 2024/11/04 | ISO with slashes. |
DD/MM/YYYY | 04/11/2024 | Day-first with slashes. |
Month DD, YYYY | Nov 04, 2024 | Full month name first. |
DD Month YYYY | 04 Nov 2024 | Day with full month. |
YYYY | 2024 | Year only. |
MM | 11 | Padded numeric month. |
mm | 11 | Unpadded numeric month. |
M | Nov | Short month name. |
DD | 04 | Padded day. |
dd | 4 | Unpadded day. |
D | Mon | Short 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".