Open In App

Node.js date-and-time Date.subtract() Method

The date-and-time Date.subtract() method is used to subtract the two date objects.

Required Module: Install the module by npm or used it locally.



npm install date-and-time --save
<script src="/path/to/date-and-time.min.js"></script>

Syntax:

const subtract(date1, date2)

Parameters: This method takes the following arguments as a parameter:



Return Value: This method returns the result object subtracting date2 from date1.

Example 1:




// Node.js program to demonstrate the  
// Date.subtract() method
  
// Importing date-and-time module
const date = require('date-and-time')
  
// Creating object of current date and time 
// by using Date() 
const now  =  new Date();
  
// Creating object of given date and time
const date1 = new Date(2015, 0, 1);
  
// Subtracting the both dates
// by using date.subtract() method
const value = date.subtract(now,date1);
  
// Display the result
console.log("total days between them " 
   + value.toDays())

Run the index.js file using the following command:

node index.js

Output:

total days between them 2270.3951833333335

Example 2:




// Node.js program to demonstrate the  
// Date.subtract() method
  
// Importing date-and-time module
const date = require('date-and-time')
  
// Creating object of current date and time 
// by using Date() 
const now  =  new Date();
  
// Setting days in the existing date
now.setDate(20);
  
// Creating object of given date and time
const date1 = new Date(2015, 0, 1);
  
// Subtracting the both dates
// by using date.subtract() method
const value = date.subtract(now,date1);
  
// Display the result
console.log("total days between them " + value.toDays())

Run the index.js file using the following command:

node index.js

Output:

total days between them 2270.397227997685

Reference: https://github.com/knowledgecode/date-and-time#subtractdate1-date2


Article Tags :