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.
time.fromNow([true])
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"
.
The value returned is a string denoting the time that has passed between the time specified and now.
Let's view a code example.
// require the moment moduleconst moment = require("moment")// create some dates and timeconst time1 = moment([2010, 1, 14, 10, 25, 50, 125])const time2 = moment(new Date) // current date and timeconst 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 nowconsole.log(time1.fromNow()) // 12 years agoconsole.log(time2.fromNow()) // a few seconds agoconsole.log(time3.fromNow(true)) // 11 years (no "ago" suffix)console.log(time4.fromNow()) // in x hoursconsole.log(time5.fromNow()) // in y monthconsole.log(time6.fromNow()) // in 3 years
moment.js
package.fromNow()
method of moment.js
to get the difference in time between the dates and time we created and the present time.