Last active
July 10, 2024 23:10
-
-
Save sdesalas/21aedca1624205d5ca4d567634f21a93 to your computer and use it in GitHub Desktop.
Minimal KISS implementation of TimeAgo.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.