docbrown/app/assets/javascripts/utilities/localDateTime.js
rhymes 4e591fea1c Show localized date/time on hover for articles/comments (#2722)
* Add article decorator published_timestamp

* Use time HTML5 element and refactor date in partial

* Add published_timestamp to Article

Adding `published_timestamp` to the homepage we can then use JS to render the full timestamp localized for the user.

We've also added the timestamp to the index and the API

* Display article published timestamp on hover

* Use time also in the article show page

* Add timestamp to bottom articles as well

* Remove published_timestamp from index because it is not used

* Fix broken specs

* Add more article dates specs

* Refactor date initializers
2019-05-09 11:05:17 -04:00

57 lines
1.6 KiB
JavaScript

/* Local date/time utilities */
/*
Convert string timestamp to local time, using the given locale.
timestamp should be something like '2019-05-03T16:02:50.908Z'
locale can be `navigator.language` or a custom locale. defaults to 'default'
options are `Intl.DateTimeFormat` options
see <https://developer.mozilla.org//docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat>
for more information.
*/
function timestampToLocalDateTime(timestamp, locale, options) {
if (timestamp === '') {
return '';
}
try {
var time = new Date(timestamp);
return new Intl.DateTimeFormat(locale || 'default', options).format(time);
} catch (e) {
return '';
}
}
function addLocalizedDateTimeToElementsTitles(elements, timestampAttribute) {
// example: "Wednesday, April 3, 2019, 2:55:14 PM"
var timeOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
};
for (var i = 0; i < elements.length; i += 1) {
var element = elements[i];
// get UTC timestamp set by the server
var timestamp = element.getAttribute(timestampAttribute || 'datetime');
if (timestamp) {
// add a full datetime to the element title, visible on hover.
// `navigator.language` is used to allow the date to be localized
// according to the browser's locale
// see <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language>
var localDateTime = timestampToLocalDateTime(
timestamp,
navigator.language,
timeOptions,
);
element.setAttribute('title', localDateTime);
}
}
}