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

Last Updated : 7 Oct, 2021

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.

  • By using npm.
npm install date-and-time --save
  • By using CDN link.
<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:

  • date1: It is the first date object from which the second date is subtracted.
  • date2: It is the second date object.

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

Example 1:

index.js
// 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:

index.js
// 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

Comment

Explore