Open In App

Moment.js moment().toNow() Function

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

The moment().toNow(Boolean) function is used to calculate the time to now in Node.js. This function is sometimes called time ago or relative time. 

Syntax:

moment().toNow(Boolean);

Parameters: This function has one optional boolean type parameter to return the value without a prefix. 

Return Value: This function returns the date. 

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]).toNow();
console.log(result);


Steps to run the program:

Run the index.js file using the below command:

node index.js

Output:

in 10 years

Example 2: Filename: index.js 

javascript




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


Steps to run the program:

Run the index.js file using the below command:

node index.js

Output:

Result: 9 years

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads