Skip to content

formatDate()

formatDate(date?, format?): string

Defined in: src/utils/dateUtils.ts:28

Formats a Date object into a string according to the specified format.

Supported placeholders in the format string:

  • YYYY: Four-digit year (e.g., 2024).
  • YY: Two-digit year (e.g., 24).
  • MM: Two-digit month (e.g., 01 for January).
  • MMM: Abbreviated month name (e.g., Jan, Feb).
  • DD: Two-digit day of the month (e.g., 09).
  • HH: Two-digit hour in 24-hour format (e.g., 15 for 3 PM).
  • mm: Two-digit minutes (e.g., 07).
  • ss: Two-digit seconds (e.g., 45).

Parameters

date?

The date to format. Can be a Date object or a string.

null | string | Date

format?

string = 'YYYY-MM-DD'

The format string. Defaults to 'YYYY-MM-DD'.

Returns

string

A formatted date string. Returns an empty string if the input is invalid.

Example

ts
const now = new Date('2024-02-18T12:34:56Z');

formatDate(now, 'YYYY-MM-DD'); // '2024-02-18'
formatDate(now, 'MMM DD, YYYY'); // 'Feb 18, 2024'
formatDate(now, 'YYYY-MM-DD HH:mm:ss'); // '2024-11-18 12:34:56'
formatDate(now, 'MM/DD/YYYY'); // '02/18/2024'

Released under the MIT License.