formatDate()
formatDate(
date
?,format
?):string
Defined in: src/utils/dateUtils.ts:26
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).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
tsx
const now = new Date('2024-11-18T12:34:56Z');
formatDate(now, 'YYYY-MM-DD'); // '2024-11-18'
formatDate(now, 'YYYY-MM-DD HH:mm:ss'); // '2024-11-18 12:34:56'
formatDate(now, 'MM/DD/YYYY'); // '11/18/2024'