• Post category:JavaScript
  • Reading time:3 mins read

Manymore developers are struggling to display time from now such as days ago, weeks ago, in N months, months/years ago, etc in JavaScript therefore today we’ll come with a new article where you will find the way to implement time from now using Moment JS.

In the previous JS article, we have explain how to convert seconds to minutes and hours in JavaScript. In today’s article we will use Moment.js to get the time difference.

Add Moment Script

Use the below moment script to get time from now.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

Display timeago

Let’s use the below method to display time that is handled by moment. Moment has two different methods .fromNow() and .fromNow(Boolean) to get output.

// Get current datetime
moment().format('lll'); // May 27, 2020 9:19 PM

moment([2020, 0, 29]).fromNow(); // 4 months ago
moment().fromNow(); // a few seconds ago
moment('25-02-2020', 'DD-MM-YYYY').fromNow(); // 3 months ago
moment('25-02-2020', 'DD-MM-YYYY').fromNow(true); // 3 months

// Use future date
moment('25-08-2020', 'DD-MM-YYYY').fromNow(); // in 3 months
moment('25-08-2020', 'DD-MM-YYYY').fromNow(true); // 3 months

The .fromNow(Boolean) method will be used to get a value without a suffix. We have already shown you the sample code in above snippets.

Check out the link for more information about the time range and output.

You can refer to one more article that we wrote in JavaScript using Moment.
Convert datetime to another time zone using Moment JS

That’s it for today.
Thank you for reading. Happy Coding..!!

Leave a Reply