TIL How to math the 6 minutes(s) ago without a library
POSTED ON:
TAGS: javascript dates
Sometimes you need something to print a date to 6 minute(s) ago
, but don't want to import monster-size libs. Here's a small snippet that does it, easily modify it as you wish and go ahead.
const fromAgo = (date) => {
const ms = Date.now() - date.getTime();
const seconds = Math.round(ms / 1000);
const minutes = Math.round(ms / 60000);
const hours = Math.round(ms / 3600000);
const days = Math.round(ms / 86400000);
const months = Math.round(ms / 2592000000);
const years = Math.round(ms / 31104000000);
switch (true) {
case seconds < 60:
return `${seconds} second(s) ago"`;
case minutes < 60:
return `${minutes} minute(s) ago"`;
case hours < 24:
return `${hours} hour(s) ago"`;
case days < 30:
return `${days} day(s) ago`;
case months < 12:
return `${months} month(s) ago`;
default:
return `${years} year(s) ago`;
}
};
const createdAt = new Date(2021, 0, 5);
fromAgo(createdAt); // 14 day(s) ago;
Via 11 JavaScript Tips and Tricks to Code Like A Superhero (Vol.2)](https://dev.to/orkhanjafarovr/11-javascript-tips-and-tricks-to-code-like-a-superhero-vol-2-mp6)
Related TILs
Tagged: javascript