Wednesday, May 13, 2015

A Definitive Way to Format Dates for International Sites

Date formats vary with region and language so, it is always helpful if we can find a way to display the dates to the users, specific to their language and region.


Back in December, 2012, ECMA released the specifications of Internationalization API for JavaScript. The Internationalization API helps us display certain data according to the language and cutural specification. It can be used to identify currencies, time zones and more.


In this post we will be looking into date formatting using this API.


Know the user’s locale


To show the date as per user’s preferred locale, first we need to know what that preferred locale is. Currently the foolproof way to know that is to ask the user; let users select their preferred language and region settings in the webpage.


But, if that is not an option you can interpret the Accept-Language request header or read the navigator.language(for Chrome and Firefox) or navigator.browserLanguage(for IE) values.


Please know that not all of those options return the preferred language of the browser UI.


 var language_tag = window.navigator.browserLanguage || window.navigator.language || "en"; // returns language tags like "en-GB" 

Check for Internationalization API


To know if the browser supports Internationalization API or not, we can check for the presence of the global object Intl.


 if(window.hasOwnProperty​("Intl") && typeof Intl === "object") // Internationalization API is present, let us use that 

The Intl object


Intl is a global object for using the Internationalization API. It has three properties which are constructors for three objects namely Collator, NumberFormat, and DateTimeFormat.


The object we will be using is DateTimeFormat which will help us format date time as per different languages.


The DateTimeFormat object


The DateTimeFormat constructor takes two optional arguments;


  • locales – a string or an array of strings that represent the language tags, for example; "de" for German language, "en-GB" for English used in United Kingdom. If a language tag is not mentioned, the default locale will be that of runtime.

  • options – an object whose properties are used to customize the formatter. It has the following properties:








































Property
Description
Possible values
dayDay of the month“2-digit”, “numeric”
eraEra the date falls into, Ex: BC “narrow”, “short”, “long”
formatMatcherThe algorithm used for format matching“basic”, “best fit”[Default]
hourRepresents Hours in the time“2-digit”, “numeric”
hour12Indicates 12-hour format(true) or 24-hour format(false)true, false
localeMatcherThe algorithm used for locale matching“lookup”, “best fit”[Default]
minuteMinutes in the time“2-digit”, “numeric”
monthMonth in a year“2-digit”, “numeric”, “narrow”, “short”, “long”
secondSeconds in the time“2-digit”, “numeric”
timeZoneTime zone to apply“UTC”, default is runtime time zone
timeZoneName Time zone of the date“short”, “long”
weekdayDay in the week“narrow”, “short”, “long”
yearYear of the date“2-digit”, “numeric”

Example:


 var formatter = new Intl.DateTimeFormat("en-GB"); /* returns a formatter that can format a date in UK English date format */ 

 var options = weekday: "short"; var formatter = new Intl.DateTimeFormat("en-GB", options); /* returns a formatter that can format a date in UK English date format * along with the weekday in short notation like "Thu" for Thursday */ 

The format function


The instance of the DateTimeFormat object has an property accessor (getter) called format which returns a function that formats a Date based on the locales and options found in the DateTimeFormat instance.


The function takes a Date object or undefined as an optional argument and returns a string in the requested date format.


Note: If the argument is either undefined or not provided then it returns the value of Date.now() in the requested date format.


Here’s the syntax:


 new Intl.DateTimeFormat().format() //will return the current date in the runtime date format 

And now let us code a simple date formatting.



Let us change the language and see the output.



Now, it is time to look into options.



The toLocaleDateString method


Instead of using a formatter like shown in the above examples, you can also use Date.prototype.toLocaleString in the same way with the locales and options arguments, they are similar but it is recommended to use the DateTimeFormat object when dealing with too many dates in your application.


 var mydate = new Date("2015/04/22"); var options = weekday: "short", year: "numeric", month: "long", day: "numeric" ; console.log(mydate.toLocaleDateString("en-GB",options)); // returns "Wed, 22 April 2015" 

Test if the locales are supported


To check for the supported locales, we can use the method supportedLocalesOf of DateTimeFormat object. It returns an array of all supporting locales or an empty array if none of the locales is supported.


For testing, let us add a dummy locale “blah” in the list of locales to be checked.


 console.log(Intl.DateTimeFormat.supportedLocalesOf(["zh","blah", "fa-pes"])); // returns Array [ "zh", "fa-pes" ] 

Browser Support


At of the end of April 2015, major browsers support the Internationalization API.


Can I Use

References


Editor’s note: This is written for Hongkiat.com by Preethi R. Preethi is a .NET Web developer with a Java past and a bias for Firefox, Windows & DC Comic movies.










A Definitive Way to Format Dates for International Sites

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.