MomentJS HTML hook
Hooks into the <time> element to automatically convert the dates/times on page load and then each 60 seconds.
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js"></script>
<!-- Be sure to update the times to be relative to the current date/time -->
<div>
<time class="cw-relative-date" datetime="2014-06-09T12:32:10-00:00">
Calculating an old time
</time>
</div>
<div>
<time class="cw-relative-date" datetime="2014-07-31T04:11:10-00:00">
Calculating a time within the current week
</time>
</div>
<div>
<time class="cw-relative-date" datetime="2014-08-03T10:11:10-00:00">
Calculating a time within the current day
</time>
</div>
<div>
<time class="somethingelse" datetime="2012-06-09T12:32:10-04:00">
Ignore me
</time>
</div>
JavaScript
(function () {
// Define a function that updates all relative dates defined by <time class='cw-relative-date'>
var updateAllRelativeDates = function() {
$('time').each(function (i, e) {
if ($(e).attr("class") == 'cw-relative-date') {
// Initialise momentjs
var now = moment();
moment.lang('en', {
calendar : {
lastDay : '[Yesterday at] LT',
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
lastWeek : '[Last] dddd [at] LT',
nextWeek : 'dddd [at] LT',
sameElse : 'D MMM YYYY [at] LT'
}
});
// Grab the datetime for the element and compare to now
var time = moment($(e).attr('datetime'));
var diff = now.diff(time, 'days');
// If less than one day ago/away use relative, else use calendar display
if (diff <= 1 && diff >= -1) {
$(e).html('<span>' + time.from(now) + '</span>');
} else {
$(e).html('<span>' + time.calendar() + '</span>');
}
}
});
};
// Update all dates initially
updateAllRelativeDates();
// Register the timer to call it again every minute
setInterval(updateAllRelativeDates, 60000);
})();