Skip to content

Instantly share code, notes, and snippets.

@sdesalas
Last active July 10, 2024 23:10
Show Gist options
  • Save sdesalas/21aedca1624205d5ca4d567634f21a93 to your computer and use it in GitHub Desktop.
Save sdesalas/21aedca1624205d5ca4d567634f21a93 to your computer and use it in GitHub Desktop.
Minimal KISS implementation of TimeAgo.
const SECOND = 1000;
const MINUTE = 60*SECOND;
const HOUR = 60*MINUTE;
const DAY = 24*HOUR;
const WEEK = 7*DAY;
const MONTH = 30*DAY;
const YEAR = 52*WEEK;
function timeAgo(date) {
const diff = Date.now() - new Date(date).getTime();
if (!diff || diff < 0) return 'some time ago';
if (diff < 1.5*MINUTE) return `a moment ago`;
if (diff < 1.5*HOUR) return Math.round(diff/MINUTE) + ' minutes ago';
if (diff < 1.5*DAY) return Math.round(diff/HOUR) + ' hours ago';
if (diff < 1.5*WEEK) return Math.round(diff/DAY) + ' days ago';
if (diff < 1.5*MONTH) return Math.round(diff/WEEK) + ' weeks ago';
if (diff < 1.5*YEAR) return Math.round(diff/MONTH) + ' months ago';
return Math.round(diff/YEAR) + ' years ago';
}
@sdesalas
Copy link
Author

sdesalas commented Jul 10, 2024

Sometimes the aim is to keep the implementation extremely simple, over trying to find the most complete and perfect solution for a problem.

This algorithm for time ago formatting (ie 10 minutes ago) is such an example. It deals with 80% and ignores 20% of use cases for the sake of brevity.

This worse is better approach is easier to understand, copy, extend and to port to other frameworks and languages.

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