Skip to content

Instantly share code, notes, and snippets.

@IbeVanmeenen
Last active April 12, 2022 14:03
Show Gist options
  • Save IbeVanmeenen/4e3e58820c9168806e57530563612886 to your computer and use it in GitHub Desktop.
Save IbeVanmeenen/4e3e58820c9168806e57530563612886 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`;
};
@IbeVanmeenen
Copy link
Author

IbeVanmeenen commented Aug 25, 2016

@IbeVanmeenen
Copy link
Author

IbeVanmeenen commented Aug 25, 2016

Updated epochs to an array because the sequence of the values is important. Properties order in objects is not guaranteed in JavaScript. Kudos to @pjaspers for pointing this one out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment