Skip to content

Instantly share code, notes, and snippets.

@petar-dambovaliev
Created February 28, 2017 10:03
Show Gist options
  • Save petar-dambovaliev/12520b6b2c81283911b0c2d49e5a5577 to your computer and use it in GitHub Desktop.
Save petar-dambovaliev/12520b6b2c81283911b0c2d49e5a5577 to your computer and use it in GitHub Desktop.
Calculates correct ago times for cached html pages
(function() {
var DateHelper = {
// Takes the format of "Jan 15, 2007 15:45:00 GMT"
// and converts it to a relative time
get_ago_time: function(fromDate) {
var from = new Date();
from.setTime(Date.parse(fromDate));
var to = new Date();
var distance_in_seconds = ((to - from) / 1000);
var distance_in_minutes = Math.floor(distance_in_seconds / 60);
if (distance_in_minutes === 0) { return 'less than a minute ago'; }
if (distance_in_minutes == 1) { return 'a minute ago'; }
if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes ago'; }
if (distance_in_minutes < 90) { return 'about 1 hour ago'; }
if (distance_in_minutes < 1440) { return 'about ' + Math.floor(distance_in_minutes / 60) + ' hours ago'; }
if (distance_in_minutes < 2880) { return '1 day ago'; }
if (distance_in_minutes < 43200) { return Math.floor(distance_in_minutes / 1440) + ' days ago'; }
if (distance_in_minutes < 86400) { return 'about 1 month ago'; }
if (distance_in_minutes < 525960) { return Math.floor(distance_in_minutes / 43200) + ' months ago'; }
if (distance_in_minutes < 1051199) { return 'about 1 year ago'; }
return 'over ' + Math.floor(distance_in_minutes / 525960) + ' years ago';
}
};
var times = document.getElementsByTagName('relative-time');
for (i = 0; i < times.length; i++) {
times[i].innerText = DateHelper.get_ago_time(times[i].getAttribute('datetime'));
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment