A Comprehensive Guide on Date Formatting for Global Websites
Mastering date formats is essential for websites with a global audience. Different regions prefer distinct date formats, and aligning with these preferences is key to user engagement and international success. This guide dives into the effective use of JavaScript’s Internationalization API, as defined by ECMA, for customizing date displays in various languages and cultural norms. Learn how to handle different date formats, currencies, and time zones with ease.
Our focus: leveraging the Internationalization API for seamless and efficient date formatting across different languages and regions.
Display Date and Time: How to Do It Right
We come across them dates and time... well, every day. When it comes to the Web, you can... Read more
Determining the User’s Locale
To display the date in the user’s preferred local format, it’s important to first identify their locale. The most straightforward method is to allow users to choose their language and regional preferences on your webpage.
If direct user selection isn’t viable, other approaches include interpreting the Accept-Language
header from user requests or utilizing the navigator.language
(for Chrome and Firefox) or navigator.browserLanguage
(for Internet Explorer) properties in JavaScript.
However, it’s important to note that these methods may not always accurately reflect the user’s browser UI language preference.
var language_tag = window.navigator.browserLanguage || window.navigator.language || "en"; // returns language tags like 'en-GB'
Verifying Internationalization API Support
To determine if a browser supports the Internationalization API, we can check for the presence of the global Intl
object.
if(window.hasOwnProperty("Intl") && typeof Intl === "object"){ // The Internationalization API is available for use }
Exploring the Intl
Object
The Intl
object in JavaScript serves as a gateway to the Internationalization API. It contains three constructor properties: Collator
for string comparison, NumberFormat
for number formatting, and DateTimeFormat
for date and time formatting. Our focus will be on DateTimeFormat
, which is instrumental in adapting date and time presentation to different languages.
Capabilities of the DateTimeFormat
Object
The DateTimeFormat
constructor in JavaScript takes two optional arguments:
locales
– This can be a string or an array of strings indicating language tags, such as “de” for German or “en-GB” for English as used in the United Kingdom. In the absence of a specific language tag, the default locale of the runtime environment is used.options
– An object whose properties allow customization of the date formatter. It includes properties such as:
Property | Description | Possible values |
day |
Day of the month | “2-digit”, “numeric” |
era |
Era in which the date falls, e.g., AD or BC | “narrow”, “short”, “long” |
formatMatcher |
Algorithm used for format matching | “basic”, “best fit” [Default] |
hour |
Hour of the day | “2-digit”, “numeric” |
hour12 |
Whether to use 12-hour format (true) or 24-hour format (false) | true , false |
localeMatcher |
Algorithm used for matching locales | “lookup”, “best fit” [Default] |
minute |
Minute of the hour | “2-digit”, “numeric” |
month |
Month of the year | “2-digit”, “numeric”, “narrow”, “short”, “long” |
second |
Second of the minute | “2-digit”, “numeric” |
timeZone |
Time zone to use for formatting | “UTC”, default to the runtime’s time zone |
timeZoneName |
Name of the time zone | “short”, “long” |
weekday |
Day of the week | “narrow”, “short”, “long” |
year |
Year | “2-digit”, “numeric” |
Example:
var formatter = new Intl.DateTimeFormat('en-GB'); // Returns a formatter for UK English date format
var options = {weekday: 'short'}; var formatter = new Intl.DateTimeFormat('en-GB', options); // Returns a formatter for UK English date format with weekday
Utilizing the format
Function
The DateTimeFormat
object includes a property accessor named format
. This function is designed to format a Date
object according to the specified locales
and options
within the DateTimeFormat
instance.
It accepts either a Date
object or undefined
as an optional argument, returning a formatted date string.
Note: If no argument is provided, or if it’s undefined
, the function defaults to formatting the current date using Date.now()
.
Here’s how it works:
new Intl.DateTimeFormat().format() // Returns the current date in the format specific to the runtime's locale
Let’s explore some simple date formatting examples:
Now, let’s see how changing the language affects the output:
Next, let’s delve into the versatility of the formatting options:
Using the toLocaleDateString
Method
As an alternative to the formatter approach, you can use Date.prototype.toLocaleDateString
for similar functionality. This method also utilizes the locales
and options
arguments. While it’s similar to using the DateTimeFormat
object, the latter is recommended for applications handling a large number of dates.
var mydate = new Date('2015/04/22'); var options = { weekday: "short", year: "numeric", month: "long", day: "numeric" }; console.log(mydate.toLocaleDateString('en-GB', options)); // Outputs "Wed, 22 April 2015"
Checking Supported locales
To determine which locales
are supported, the DateTimeFormat
object’s supportedLocalesOf
method can be used. This method returns an array of all supported locales or an empty array if none are supported. For example, to test, we can include a fictitious locale “blah” among the locales being checked.
console.log(Intl.DateTimeFormat.supportedLocalesOf(["zh", "blah", "fa-pes"])); // Outputs Array [ "zh", "fa-pes" ]
References
- ECMA International: ECMAScript Internationalization API Specification
- IANA: Language Subtag Registry
- Norbert’s Corner: Understanding the ECMAScript Internationalization API