Back to JavaScript
2025-12-208 min read

Date and time formatting (JavaScript)

Learn Date and time formatting (JavaScript) step by step with clear examples and exercises.

Title: Mastering JavaScript Date and Time Formatting with the Intl API

Why This Matters

In web development, handling dates and times effectively is crucial for creating dynamic interfaces, scheduling tasks, and building applications that interact with user-generated data. The Internationalization API (Intl) offers an advanced solution for handling locale-specific date formatting and other localized features, making it easier to format dates and times according to different cultures and languages.

Prerequisites

Before diving into the core concept, you should have a good understanding of:

  1. Basic JavaScript concepts such as variables, functions, control structures, and ES6 syntax (including arrow functions).
  2. The JavaScript Date object for creating and manipulating dates.
  3. Understanding the basics of working with HTML and CSS to structure your web application.
  4. Familiarity with browser compatibility issues and how to handle them using feature detection or polyfills.

Core Concept

The Intl API provides a wide range of locale-specific data and operations, making it easier to format dates and times according to different cultures and languages. It includes several objects for various use cases:

  1. Intl.DateTimeFormat: Formats dates and times based on the specified locale.
  2. Intl.NumberFormat: Formats numbers according to a specific locale.
  3. Intl.Collator: Provides collation (i.e., comparing strings for sorting or searching) functionality.
  4. Intl.PluralRules: Helps select the correct plural form of a word based on the specified locale.
  5. Intl.Segmenter: Segments text into units like words, sentences, or graphemes according to the specified locale.
  6. Intl.RelativeTimeFormat: Formats relative time, such as "2 days ago" or "next Tuesday."

Using Intl.DateTimeFormat

To format dates and times using Intl.DateTimeFormat, follow these steps:

  1. Create a new instance of the object, passing in the desired locale (e.g., 'en-US') and options like time zone or date style.
  2. Call the format() method on the instance, providing the date as a JavaScript Date object or as a string representing a date.

Here's an example:

const options = { year: 'numeric', month: 'long', day: 'numeric' };
const date = new Date();
const formattedDate = Intl.DateTimeFormat('en-US', options).format(date);
console.log(formattedDate); // Outputs "January 31, 2023"

Formatting Options

The options object allows you to customize the formatting of your date. Commonly used properties include:

  • year: The year format (numeric, 2-digit, or narrow).
  • month: The month format (numeric, long, short, or narrow).
  • day: The day format (numeric, long, short, or narrow).
  • hour: The hour format (numeric, 2-digit, or zero-padded).
  • minute: The minute format (numeric, 2-digit, or zero-padded).
  • second: The second format (numeric, 2-digit, or zero-padded).
  • timeZone: The time zone to use for the formatted date.
  • weekday: The day of the week format (numeric, long, short, or narrow).
  • era: The era format (numeric, short, long, or narrow).
  • hour12: Whether to use 12-hour clock format (true) or 24-hour clock format (false).

Time Zone Support

The Intl API supports both IANA time zones and browser-specific time zones. To specify a time zone, include it in the options object like so:

const options = { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'America/Los_Angeles' };
// ...
Intl.DateTimeFormat('en-US', options).format(date); // Outputs "January 31, 2023 Pacific Standard Time"

Worked Example

Let's create a simple date picker that formats the selected date based on the user's locale:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date Picker</title>
<style>
#datePicker { display: flex; }
input[type=range] { width: 100%; }
</style>
</head>
<body>
<h1>Date Picker</h1>
<div id="datePicker">
<input type="range" min="1900" max="2100" value="2023" id="year" onchange="updateDate()">
<input type="range" min="1" max="12" value="1" id="month" onchange="updateDate()">
<input type="range" min="1" max="31" value="1" id="day" onchange="updateDate()">
</div>
<p id="formattedDate"></p>

<script>
function updateDate() {
const year = document.getElementById('year').value;
const month = document.getElementById('month').value;
const day = document.getElementById('day').value;
const date = new Date(year, month - 1, day); // Months are zero-indexed in JavaScript

const options = { year: 'numeric', month: 'long', day: 'numeric' };
const formattedDate = Intl.DateTimeFormat('en-US', options).format(date);
document.getElementById('formattedDate').textContent = formattedDate;
}
</script>
</body>
</html>

Common Mistakes

  1. Not providing a locale: Always specify the desired locale when using Intl.DateTimeFormat. If you don't, it will default to the browser's current locale, which may not be what you intended.
  2. Incorrectly formatting options: Make sure that the date style and time zone options are correctly set according to your needs. For example, if you want a full date with time, use { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' }.
  3. Not handling invalid dates: When working with user input, ensure that the provided date is valid and falls within the range of possible values for the year, month, and day.
  4. Ignoring browser compatibility: While most modern browsers support the Intl API, it's essential to consider older browsers or devices that may not have full support. You can use feature detection or polyfills to ensure your application works across various platforms.

Common Mistakes (cont.)

  1. Not considering daylight saving time: When working with dates and times, be aware of daylight saving time changes and adjust your code accordingly if necessary.
  2. Misunderstanding the difference between locales and languages: Locales are a combination of language and region, so make sure to choose the appropriate locale for your specific use case.
  3. Not testing with multiple locales: To ensure that your application works correctly across various cultures and languages, test it with different locales and adjust formatting options as needed.
  4. Assuming all browsers support the same set of locales: While most modern browsers share a common set of locales, some may have additional or unique locales. Be aware of these differences when working with specific browsers.
  5. Not handling missing translations gracefully: If a translation is not available for a given locale, it's essential to provide an alternative format or fallback mechanism to ensure that the date is still correctly formatted.

Practice Questions

  1. Write a function that formats a given date as "MM/DD/YYYY" using the Intl API and the current user's locale.
  2. Implement an age calculator that asks for the user's birthday, calculates their age based on today's date, and displays the result formatted according to the user's locale.
  3. Create a simple calendar application that uses the Intl API to display dates in the user's preferred format.
  4. Extend the date picker example to include time selection (hour, minute, second) and display the full date and time in the desired format.
  5. Implement a function that converts a given timestamp into a formatted string using the Intl API and the current user's locale.
  6. Write a function that determines whether a given date is within a specific range (e.g., between two dates) using the Intl API.
  7. Create an internationalized countdown timer for a specific event, allowing users to choose their preferred date format and time zone.
  8. Implement a function that formats numbers according to the user's locale using Intl.NumberFormat.

FAQ

  1. Why should I use the Intl API for date formatting instead of the built-in JavaScript Date object? The Intl API offers more advanced features, such as locale-specific formatting and plural rules, making it easier to create applications that cater to users from different cultures and languages.
  2. What if my desired locale is not supported by the Intl API? While the Intl API supports a wide range of locales, there may be cases where your desired locale is not included. In such situations, you can either use a polyfill or manually implement the formatting rules for that specific locale.
  3. How do I handle date formats that are not supported by the Intl API? If the desired format is not available in the Intl API, you can still use the built-in JavaScript Date object to manipulate dates and create custom formatting functions based on your requirements.
  4. What is the difference between Intl.DateTimeFormat and Intl.NumberFormat? While both objects are part of the Intl API, Intl.DateTimeFormat is used for formatting dates and times, while Intl.NumberFormat is used for formatting numbers according to a specific locale.
  5. How can I ensure that my application works across different browsers and devices? To ensure compatibility, use feature detection or polyfills to support older browsers and devices that may not have full Intl API support. Additionally, test your application on various platforms to identify any potential issues.
  6. What is the difference between IANA time zones and browser-specific time zones? IANA (Internet Assigned Numbers Authority) time zones are standardized and universally recognized, while browser-specific time zones may vary depending on the browser or device being used. Browser-specific time zones typically include both IANA time zones and additional local time zones specific to that browser or device.
  7. How can I handle daylight saving time changes when using the Intl API? To handle daylight saving time changes, you should ensure that your date objects are set to the correct time zone (including DST if applicable) and use the appropriate formatting options for displaying dates and times. Additionally, consider adjusting your code to account for DST changes when necessary.
  8. How can I create custom date formats using the Intl API? To create custom date formats, you can combine various formatting options in the options object passed to Intl.DateTimeFormat. For example, to format a date as "MM/DD/YYYY", use { month: '2-digit', day: '2-digit', year: 'numeric' }.
  9. What is the best way to test my application for compatibility with different locales and browsers? To test your application, you should create a comprehensive list of locales and browsers to cover various combinations. You can use tools like BrowserStack or Sauce Labs to run automated tests across multiple platforms. Additionally, manually testing your application on different devices and browsers is essential for identifying any compatibility issues.
Date and time formatting (JavaScript) | JavaScript | XQA Learn