Skip to content

Instantly share code, notes, and snippets.

@gt3
Forked from IbeVanmeenen/timeago.js
Created January 20, 2018 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gt3/31fcf3ef86d3366a33ca49164d460050 to your computer and use it in GitHub Desktop.
Save gt3/31fcf3ef86d3366a33ca49164d460050 to your computer and use it in GitHub Desktop.
TimeAgo - ES6
// Epochs
const epochs = [
['year', 31536000],
['month', 2592000],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1]
];
// Get duration
const getDuration = (timeAgoInSeconds) => {
for (let [name, seconds] of epochs) {
const interval = Math.floor(timeAgoInSeconds / seconds);
if (interval >= 1) {
return {
interval: interval,
epoch: name
};
}
}
};
// Calculate
const timeAgo = (date) => {
const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
const {interval, epoch} = getDuration(timeAgoInSeconds);
const suffix = interval === 1 ? '' : 's';
return `${interval} ${epoch}${suffix} ago`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment