Node.js 日期和时间 Date.subtract() 方法
日期和时间 Date.subtract()方法用于减去两个日期对象。
所需模块:通过 npm 安装模块或在本地使用它。
- 通过使用 npm。
npm install date-and-time --save
- 通过使用 CDN 链接。
句法:
const subtract(date1, date2)
参数:此方法采用以下参数作为参数:
- date1:它是减去第二个日期的第一个日期对象。
- date2:它是第二个日期对象。
返回值:此方法返回从 date1 中减去 date2 的结果对象。
示例 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())
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())
使用以下命令运行index.js文件:
node index.js
输出:
total days between them 2270.3951833333335
示例 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())
使用以下命令运行index.js文件:
node index.js
输出:
total days between them 2270.397227997685
参考:https://github.com/knowledgecode/date-and-time#subtractdate1-date2