How do I format a date in JavaScript?

To format a date in JavaScript, you can use the following approaches:

1. Manual Formatting with Date Methods

Extract date components and format them with padding for consistent results:

function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`; // e.g., "2023-10-05"
}

const today = new Date();
console.log(formatDate(today));

2. Use toISOString() for UTC Dates

Extract the date portion from an ISO string (UTC time):

const date = new Date();
const isoString = date.toISOString(); // "2023-10-05T14:48:00.000Z"
const formattedDate = isoString.split('T')[0]; // "2023-10-05"

3. Intl.DateTimeFormat (Locale-Sensitive)

Format dates according to locale, with options for customization:

const date = new Date();
const options = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  timeZone: 'America/New_York'
};

const formatter = new Intl.DateTimeFormat('en-US', options);
const formattedDate = formatter.format(date); 
// Example output: "10/05/2023, 10:48 AM"

4. Custom Time Formatting

Include time components with padding:

function formatDateTime(date) {
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${formatDate(date)} ${hours}:${minutes}:${seconds}`;
  // e.g., "2023-10-05 14:48:00"
}

5. Use External Libraries

For complex formatting, consider libraries like:

  • Moment.js (legacy):
  moment().format('YYYY-MM-DD HH:mm:ss');
  • date-fns (modern):
  import { format } from 'date-fns';
  format(new Date(), 'yyyy-MM-dd HH:mm:ss');

Key Notes

  • Zero-Based Months: getMonth() returns 0 (January) to 11 (December).
  • Padding: Use .padStart(2, '0') to ensure two digits (e.g., 505).
  • Time Zones: toISOString() returns UTC time. Use Intl.DateTimeFormat with timeZone for local or specific time zones.

Choose the method that best fits your needs for simplicity, localization, or precision!

Leave a Reply

Your email address will not be published. Required fields are marked *