Open In App

Moment.js moment().fromNow() Function

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().fromNow() function is used to calculate the time from now in Node.js. This function returns the time, spend from the date which is passed in the parameter. 

Syntax:

moment().fromNow(Boolean);

Parameters: This function has one optional boolean parameter which is passed to get the value without the suffix. 

Return Value: This function returns the date calculated. 

Installation of moment module:

You can visit the link to the Install moment module. You can install this package by using this command.

npm install moment

After installing the moment module, you can check your moment version in the command prompt using the command.

npm version moment

Project Structure:

After that, you can just create a folder and add a file, for example, index.js as shown below.

Example 1: Filename: index.js 

javascript




// Requiring the module
const moment = require('moment');
  
// Function call
let  result = moment([2010, 8, 24]).fromNow();
console.log(result);


Steps to run the program:

Run the index.js file using the below command:

node index.js

Output:

10 years ago

Example 2: Filename: index.js 

javascript




// Requiring the module
const moment = require('moment');
  
function timeFromNow(date){
   return moment([2015, 8, 24]).fromNow(true);
}
  
// Function call
let  result = timeFromNow(moment);
console.log("Result:", result);


Steps to run the program:

Run the index.js file using the below command:

node index.js

Output:

Result: 5 years

Reference: https://momentjs.com/docs/#/displaying/fromnow/


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads