Monday, 26 May 2014

Displaying dates in the user's long/short date format in your Firefox extension

Following on from an issue with the date format in Easy Copy since Firefox 29, I've found an easy way to get the date or time in the long or short date formats from JavaScript in a Firefox extension.

Easy Copy used to use Date.toLocaleDateString() to get the long date but this method stopped working correctly in Firefox 29 and just returned the date in a default format. The changes were made to enable the ECMAScript internationalization API in Firefox.

In this post, I'll explain how to get the long date and short date formats consistently.

Use nsIScriptableDateFormat

To be clear, the long date format is usually set on an operating system level (Region Settings on Windows) and is normally of the format "dd MMMM yyyy" which displays as 12 October 2014. The short date format is normally... shorter, so "dd/MMM/yyyy" giving 12/10/2014. It's not the browser locale but the actual machine's format.

If you want to consistently get the long date, then call nsIScriptableDateFormat and pass it the current time.

Here's a sample JavaScript for getting the long date:
var dateFormatter = Components.classes[";1"].getService(Components.interfaces.nsIScriptableDateFormat);
var date = new Date();
dateFormatter.FormatDate("", Ci.nsIScriptableDateFormat.dateFormatLong, date.getFullYear(), date.getMonth() + 1, date.getDate());

If you want the short date format, then just pass nsIScriptableDateFormat.dateFormatShort instead of nsIScriptableDateFormat.dateFormatLong.

You can also get the long time format:
var dateFormatter = Components.classes[";1"].getService(Components.interfaces.nsIScriptableDateFormat);
var date = new Date();
dateFormatter.FormatTime("", Ci.nsIScriptableDateFormat.timeFormatSeconds, date.getHours(), date.getMinutes(), date.getSeconds());

nsIScriptableDateFormat seems to be preferred by other developers as well so I'm going with that for now. And it may work out to be more flexible than Date.toLocaleDateString() because now there's a potential for new Easy Copy variables such as %date_short% and %time_short%.

No comments:

Post a Comment