Skip to content

formatDate()

formatDate(input?, format?): string

Defined in: utils/date/formatDate.ts:35

Formats a date-like value 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 (01–12).
  • MMM: Abbreviated English month name (Jan, Feb, ...).
  • DD: Two-digit day of the month (01–31).
  • HH: Two-digit hour in 24-hour format (00–23).
  • mm: Two-digit minutes (00–59).
  • ss: Two-digit seconds (00–59).

Parameters

input?

The date to format. When omitted or null, the current time is used.

  • Date: used as-is.
  • string / number: passed to the Date constructor.

string | number | Date | null

format?

string = 'YYYY-MM-DD'

Format pattern string. Tokens are case-sensitive.

Returns

string

The formatted date string. Returns an empty string for invalid input.

Example

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

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

Released under the MIT License.