Simple Date and Time Localization With JavaScript

Share this article

One of the many challenges we’ve encountered during our work on SitePoint Contests and Marketplace is deciding the best way to present dates and times to our users. This sounds simple, but there’s quite a few considerations that we need to keep in mind. Easily Readable by Humans “Started 2 hours ago” and “Ends in 2 days” are much easier to understand than “Started Mon, 4 June 2007, 10:04am +1000” and “Ends Wed, 6 June 2007, 9:28am +1000”. Cachable by Search Engines “Started 2 hours ago” or “Ends in 2 days” are meaningless when looking at a snippet or full copy of a page cached by a search engine 2 days ago. Likewise, “Started Mon, 4 June 2007, 10:04am +1000” is difficult to understand for a person in a completely different time zone. Cachable for Performance We like to be able to allocate cache lifetimes to as many parts of our pages as possible. The text “Started Mon, 4 June 2007, 10:04am +1000” needs no cache expiry, while “Started less than a minute ago” could only be reliably cached for 1 second. Local Time While most people can figure out what “Started Mon, 4 June 2007, 10:04am GMT” means in their local time zone, it would be most valuable if we could do the sums for them, so they don’t need to spend 30 seconds figuring out that the auction ended… 1 second ago. Stale Pages Because life wasn’t complicated enough already, tabbed browsing was invented so that we can force even more input into our heads at once. Tabs also makes it easy to get side tracked for hours before coming back to that SitePoint Marketplace listing. But currently there’s no way of knowing that the auction which says “Ends in 28 minutes” is actually long gone. A Micro Solution To solve all these problems in one fell swoop, we’ve created a very simple in-house microformat and some clever JavaScript. Together, they let us present dates and times in a way which is useful, meaningful and accessible to all users. We start with some basic HTML markup: <span class="sitepoint-datetime">Mon, 28 May 2007 01:30:49 GMT</span> This will be seen by users without JavaScript, and some users of assistive technology. It may not be as pretty as “7 days ago”, but it’s the most correct, meaningful and cachable format when we don’t know how, when or where the page is actually being viewed. We’ve prefixed the class name with “sitepoint-” to make it clear that this is not a standard microformat. We’ve used RFC 2822 formatting for the date/time, which is easily read by humans, and can also be passed straight into the constructor of a JavaScript Date object. Our JavaScript finds all instances of this microformat, and converts them to the users local time, displaying it in a friendly format without an ugly time zone identifier hanging off the end. We can then add additional information to the class attribute of the span. The JavaScript code uses these to decide the best way to display the information. For example, with an extra class of “endtime”, the JavaScript will convert the time to a countdown, displaying it in a format like “1 day, 3 hours”. The time remaining is recalculated every 30 seconds, so there’s no more stale information on left-open browser tabs. The script will even visually mark contests and auctions as having ended once the countdown reaches zero. We’re looking forward to getting these and many other enhancements online over at the Design Contests and Marketplace. In the mean time, I’m sure there’s many views out there regarding such use of microformats and JavaScript, and even whether the term “microformats” is applicable to this markup pattern. Please, bring them on.

Frequently Asked Questions on JavaScript Localization

What is the importance of JavaScript localization in web development?

JavaScript localization is crucial in web development as it allows developers to create applications that can adapt to different languages, cultures, and regions. This is particularly important for businesses that operate globally, as it ensures that their applications are accessible and user-friendly to a diverse range of users. Localization not only involves translating the content into different languages but also includes formatting date and time, numbers, and currencies according to the local conventions. This enhances the user experience and can significantly impact the success of a web application.

How can I use the JavaScript Intl object for localization?

The JavaScript Intl object is a built-in object that provides a set of functionalities for internationalization. It includes several constructors, such as Intl.DateTimeFormat, Intl.NumberFormat, and Intl.Collator, which can be used for date and time formatting, number formatting, and string comparison, respectively. To use the Intl object, you need to create an instance of the desired constructor and call the appropriate method. For example, to format a date, you can use the Intl.DateTimeFormat constructor as follows:

let date = new Date();
let formatter = new Intl.DateTimeFormat('en-US');
console.log(formatter.format(date));

What are the steps involved in JavaScript localization?

JavaScript localization involves several steps. First, you need to identify the locales you want to support and gather the localized content for each locale. This includes not only the text content but also date and time formats, number formats, and other locale-specific conventions. Next, you need to implement the localization logic in your JavaScript code. This can be done using the built-in Intl object or third-party libraries like i18next. Finally, you need to test your application thoroughly to ensure that the localization works correctly for all supported locales.

Can I use third-party libraries for JavaScript localization?

Yes, there are several third-party libraries available for JavaScript localization, such as i18next, moment.js, and Globalize. These libraries provide a more comprehensive set of features compared to the built-in Intl object, making it easier to implement complex localization requirements. However, they also add an extra layer of complexity and may increase the size of your JavaScript bundle, so you should consider your specific needs and constraints before deciding to use a third-party library.

How can I handle pluralization in JavaScript localization?

Handling pluralization in JavaScript localization can be tricky, as different languages have different rules for plural forms. However, the Intl.PluralRules constructor can help with this. It provides a method to determine the plural form of a given number according to a specific locale. Here’s an example:

let pluralRules = new Intl.PluralRules('en-US');
console.log(pluralRules.select(1)); // outputs "one"
console.log(pluralRules.select(2)); // outputs "other"

In this example, the select method returns “one” for the number 1 and “other” for the number 2, which corresponds to the plural rules of English. You can use this method to determine the correct plural form and display the appropriate localized string.

Paul AnnesleyPaul Annesley
View Author

Paul is a Rails and PHP developer in the SitePoint group of companies.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form