Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Format Dates in JavaScript

1 min read .
Format Dates in JavaScript

JavaScript provides several built-in ways to format dates. For user-facing text, Intl.DateTimeFormat is usually the best starting point because it understands locales and formatting options.

toLocaleDateString()

const date = new Date();

console.log(date.toLocaleDateString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
}));

Intl.DateTimeFormat

Create a reusable formatter when formatting many values:

const formatter = new Intl.DateTimeFormat('en-GB', {
  weekday: 'long',
  year: 'numeric',
  month: 'short',
  day: 'numeric',
});

console.log(formatter.format(new Date()));

You can specify a time zone explicitly:

const formatter = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'long',
  timeStyle: 'short',
  timeZone: 'Asia/Jakarta',
});

ISO 8601

toISOString() is useful for machine-readable UTC timestamps:

console.log(new Date().toISOString());
// 2024-08-28T12:34:56.789Z

Do not use an ISO timestamp as a substitute for localized display text unless that is intentionally the format users should see.

Manual YYYY-MM-DD

For a local calendar date:

const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');

console.log(`${year}-${month}-${day}`);

Be clear about whether your application means local time or UTC; mixing them is a common source of date bugs.

Libraries

Libraries such as date-fns, Luxon, or Day.js can help with parsing, calendar arithmetic, and more complex workflows. For ordinary formatting, built-in Intl APIs are often enough.

Conclusion

Use Intl.DateTimeFormat for localized output, toISOString() for UTC machine-readable timestamps, and explicit time-zone handling whenever the same instant can be viewed in different regions.

Related Posts

chevron-up