DEV Community

Discussion on: πŸ¦Έβ€β™‚οΈ 11 JavaScript Tips and Tricks to Code Like A Superhero (Vol.2)

Collapse
 
reflexgravity profile image
Joel D Souza
case days < 30:
      return `${days} day(s) ago`;

Enter fullscreen mode Exit fullscreen mode

This will not work for months with 31 days.

Collapse
 
orkhanjafarovr profile image
Orkhan Jafarov • Edited

It's a just simple version for that formatter. That's why it shows average time.
But it's okay with 31 days. If it's more than 30 days then 1 month;

example

new Date(2021, 0, 31); // now - 2021-01-30T20:00:00.000Z
const createdAt = new Date(2021, 0, 1); // 2020-12-31T20:00:00.000Z
fromAgo(createdAt); // 1 month(s) ago
Enter fullscreen mode Exit fullscreen mode

You can also replace Date.now() with your own date to check with date.getTime()