What is the fromNow() method in moment.js?

Overview

The moment.js package is a node module that allows us to manipulate dates and times according to our preferences. The fromNow() method, for instance, will enable us to get the difference in time between one time and the present time.

Syntax

time.fromNow([true])
Syntax for fromNow() method in Momen.js

Parameters

time: This is the time we want to check, to see how far it is from the current time.

true: This is used to remove the suffix "ago".

Return value

The value returned is a string denoting the time that has passed between the time specified and now.

Example

Let's view a code example.

// require the moment module
const moment = require("moment")
// create some dates and time
const time1 = moment([2010, 1, 14, 10, 25, 50, 125])
const time2 = moment(new Date) // current date and time
const time3 = moment(1318781876406)
const time4 = moment({hour: 20, minute: 20, second: 34})
const time5 = moment([2022, 5, 17])
const time6 = moment([2025, 4, 18])
// get time from now
console.log(time1.fromNow()) // 12 years ago
console.log(time2.fromNow()) // a few seconds ago
console.log(time3.fromNow(true)) // 11 years (no "ago" suffix)
console.log(time4.fromNow()) // in x hours
console.log(time5.fromNow()) // in y month
console.log(time6.fromNow()) // in 3 years

Explanation

  • Line 2: We require the moment.js package.
  • Lines 5–10: We create some dates and times.
  • Lines 13–18: We use the fromNow() method of moment.js to get the difference in time between the dates and time we created and the present time.

Free Resources