avatar

Le Do Nghiem

Software Engineer

  • About me
  • Books
  • Snippets
  • Blog

© 2026 Le Do Nghiem. All rights reserved.

Contact |

Back to Snippets

formatDate Function

Format dates consistently across your application with a simple utility function.

LanguageTypeScript
Last UpdatedDec 21, 2025
format-date.ts
export function formatDate(
  date: Date | string | number,
  options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  }
): string {
  const dateObj = typeof date === 'string' || typeof date === 'number'
    ? new Date(date)
    : date;

  return new Intl.DateTimeFormat('en-US', options).format(dateObj);
}

Formatting dates consistently is crucial for a good user experience. This utility function provides a clean way to format dates in various styles.

export function formatDate(
  date: Date | string | number,
  options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  }
): string {
  const dateObj = typeof date === 'string' || typeof date === 'number'
    ? new Date(date)
    : date;

  return new Intl.DateTimeFormat('en-US', options).format(dateObj);
}

How It Works

  • Accepts Date objects, strings, or timestamps.
  • Uses Intl.DateTimeFormat for internationalization support.
  • Provides sensible defaults but allows customization.

Example Usage

// Default format: "April 28, 2025"
formatDate(new Date());

// Custom format: "04/28/2025"
formatDate(new Date(), {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
});

// Short format: "Apr 28, 2025"
formatDate(new Date(), {
  year: 'numeric',
  month: 'short',
  day: 'numeric',
});

// With time: "April 28, 2025, 3:45 PM"
formatDate(new Date(), {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: '2-digit',
});

Common Patterns

// Relative time (requires additional logic)
function formatRelativeTime(date: Date): string {
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (days === 0) return 'Today';
  if (days === 1) return 'Yesterday';
  if (days < 7) return `${days} days ago`;
  return formatDate(date);
}

Use Cases

  • Displaying blog post dates
  • Showing timestamps in comments
  • Formatting user registration dates
  • Displaying event dates
  • Creating readable timestamps

Notes

  • Uses the browser's built-in internationalization API.
  • Automatically handles timezone based on user's locale.
  • For relative time ("2 hours ago"), consider libraries like date-fns or dayjs.
  • The function is locale-aware and can be extended to support other locales.

A simple, flexible date formatting utility that works with any date format and provides consistent output.

Previous Snippet

generateId Function

Next Snippet

deepClone Function