How to show seconds/minutes or years ago using javascript

The problem

We have a string like "2018-03-29 12:24:22.886816" and we want to show the user a nicer format like " 30 minutes ago".

To install moment use:

npm install moment

Solution

Moment is a great library and it allows to parse many date formats:

var solution_date = moment("2018-03-29 12:24:22.886816");

To show "moments ago" use:

console.log(solution_date.fromNow());

Leonardo Lazzaro

Software engineer and technical writer. 10+ years experience in DevOps, Python, and Linux systems.

More articles by Leonardo Lazzaro