Today I Learned - Rocky Kev

TIL How to math the 6 minutes(s) ago without a library

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.