Commit f6e7bda8 authored by Robert Knight's avatar Robert Knight

Optimize timestamp formatting

Date.toLocaleDateString() with options is extremely slow,
creating and re-using an Intl.DateTimeFormat object is two
orders of magnitude faster (see #2820)

Fixes #2820
parent b8140413
var DATE_SUPPORTS_LOCALE_OPTS = (function () {
try {
// see http://mzl.la/1YlJJpQ
(new Date).toLocaleDateString('i');
} catch (e) {
if (e instanceof RangeError) {
return true;
}
}
return false;
})();
// cached date formatting instance.
// See https://github.com/hypothesis/h/issues/2820#issuecomment-166285361
var formatter;
/**
* Returns a standard human-readable representation
* of a date and time.
*/
function format(date) {
if (DATE_SUPPORTS_LOCALE_OPTS) {
return date.toLocaleDateString(undefined, {
if (typeof Intl !== 'undefined' && Intl.DateTimeFormat) {
if (!formatter) {
formatter = new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'short',
day: '2-digit',
......@@ -24,6 +17,8 @@ function format(date) {
hour: '2-digit',
minute: '2-digit',
});
}
return formatter.format(date);
} else {
// IE < 11, Safari <= 9.0.
// In English, this generates the string most similar to
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment