Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

formatDate

Formats a Date object using a custom format string and locale.

TypeScript
Copied!
1/**
2 * Formats a Date object using a custom format string and locale.
3 *
4 * Supported tokens:
5 * - YYYY: full year
6 * - MM: month (01–12)
7 * - DD: day of month (01–31)
8 * - HH: hours (00–23)
9 * - mm: minutes (00–59)
10 * - ss: seconds (00–59)
11 *
12 * @param date - The Date object to format.
13 * @param format - The format string (e.g., "YYYY-MM-DD HH:mm").
14 * @param locale - Optional locale to use for month/day names (not used in basic tokens).
15 * @returns Formatted date string.
16 */
17export function formatDate(
18  date: Date,
19  format: string,
20  locale: string = 'en-US'
21): string {
22  const pad = (n: number) => n.toString().padStart(2, '0');
23
24  const replacements: Record<string, string> = {
25    YYYY: date.getFullYear().toString(),
26    MM: pad(date.getMonth() + 1),
27    DD: pad(date.getDate()),
28    HH: pad(date.getHours()),
29    mm: pad(date.getMinutes()),
30    ss: pad(date.getSeconds()),
31  };
32
33  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, token => replacements[token]);
34}
  • Custom Format String Support

    Allows developers to define date formats explicitly using familiar tokens like YYYY-MM-DD HH:mm, providing full control over output.

  • Lightweight Implementation

    Offers formatting functionality without depending on large libraries like moment.js, making it ideal for lightweight projects.

  • Consistent Zero-Padding

    Ensures that numeric components like hours or months are always two digits, improving consistency and readability.

  • Safe Token Replacement

    Uses a predictable and controlled replace with regex, preventing issues from malformed templates or unsupported characters.

  • Locale Parameter for Future Flexibility

    While current tokens are numeric, the locale parameter sets the stage for potential future support of localized names (e.g., month/day names).

Tests | Examples

TypeScript
Copied!
1test('formats date as YYYY/MM/DD', () => {
2  const date = new Date('2025-06-27T15:45:30');
3  expect(formatDate(date, 'YYYY/MM/DD')).toBe('2025/06/27');
4});
5
6test('formats date with time using dots', () => {
7  const date = new Date('2025-06-27T15:45:30');
8  expect(formatDate(date, 'YYYY.MM.DD HH.mm.ss')).toBe('2025.06.27 15.45.30');
9});
10
11test('formats single-digit components with leading zero (using slash)', () => {
12  const date = new Date('2025-03-05T07:09:02');
13  expect(formatDate(date, 'DD/MM/YYYY HH:mm:ss')).toBe('05/03/2025 07:09:02');
14});
15
16test('formats date with time and dot date separator', () => {
17  const date = new Date('2025-12-09T01:02:03');
18  expect(formatDate(date, 'DD.MM.YYYY HH:mm:ss')).toBe('09.12.2025 01:02:03');
19});
20
21test('returns empty string on empty format', () => {
22  const date = new Date('2025-06-27');
23  expect(formatDate(date, '')).toBe('');
24});

Common Use Cases

  • Generating Timestamps for Logs

    Create standardized and human-readable time formats for log entries.

  • Displaying Dates in UI Components

    Render formatted dates in dashboards, tables, or detail views.

  • Filename Generation

    Produce timestamp-based filenames (e.g., backup-2025-07-04_16-30.txt).

  • Form Inputs or Reports

    Format dates for CSV/Excel export or backend form submissions in expected formats.

  • Date Serialization for External APIs

    Output clean, formatted dates when interfacing with third-party APIs that require specific string formats.

Codebase: Utilities -> Dates -> formatDate | Yevhen Klymentiev