-
-
Save vladimirmyshkovski/7facd0fdfef2761b8f2527a3bea0c98c to your computer and use it in GitHub Desktop.
Get a time ago human friendly string from a date (like dates in twitter).
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 MINUTE = 60, | |
HOUR = MINUTE * 60, | |
DAY = HOUR * 24, | |
YEAR = DAY * 365; | |
function getTimeAgo(date) { | |
const secondsAgo = Math.round((+new Date() - date) / 1000); | |
if (secondsAgo < MINUTE) { | |
return secondsAgo + "s"; | |
} else if (secondsAgo < HOUR) { | |
return Math.floor(secondsAgo / MINUTE) + "m"; | |
} else if (secondsAgo < DAY) { | |
return Math.floor(secondsAgo / HOUR) + "h"; | |
} else if (secondsAgo < YEAR) { | |
return date.toLocaleString("default", { day: "numeric", month: "short" }); | |
} else { | |
return date.toLocaleString("default", { year: "numeric", month: "short" }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment