Moment.js moment().subtract() 方法

Moment.js moment().subtract() 方法

moment().subtract() 方法 用于从 Moment 对象中减去给定的时间单位。可以以所有被识别的单元的变种来指定单位,包括其复数和简写形式。

语法:

moment().subtract(Number, String)
OR
moment().subtract(Duration)
OR
moment().subtract(Object)

参数: 此方法接受多个参数,如上所述并在下面描述:

  • Number: 这是一个数字,表示要减去的时间值。
  • String: 这是一个字符串,表示要减去的时间单位。
  • Duration: 这是一个Duration对象,包含需要减去的时间。
  • Object: 这是一个对象,可以用来表示可以从Moment减去的所有时间值。

返回值: 此方法从Moment对象返回给定时间单位的字符串。

注意: 此方法在普通的Node.js程序中不起作用,因为它需要全局安装或项目目录中安装外部moment.js库。

可以使用以下命令安装Moment.js:

安装moment模块:

npm install moment

下面的示例将演示 Moment.js 的 moment().subtract() 方法

示例1:

const moment = require('moment'); 
  
let momentA = moment(); 
console.log( 
    "Current MomentA is:", momentA.toString() 
); 
  
momentA.subtract(5, 'hours'); 
console.log( 
    "Current MomentA is:", momentA.toString() 
); 
  
momentA.subtract(15, 'minutes'); 
console.log( 
    "Current MomentA is:", momentA.toString()); 
  
momentA.subtract(2, 'days'); 
console.log( 
    "Current MomentA is:", momentA.toString() 
); 
  
momentA.subtract(2, 'months'); 
console.log( 
    "Current MomentA is:", momentA.toString() 
); 
  
momentA.subtract(10, 'years'); 
console.log( 
    "Current MomentA is:", momentA.toString() 
);

输出:

Current MomentA is: Tue Jul 26 2022 01:24:42 GMT+0530
Current MomentA is: Tue Jul 26 2022 11:24:42 GMT+0530
Current MomentA is: Tue Jul 26 2022 12:09:42 GMT+0530
Current MomentA is: Sun Jul 31 2022 12:09:42 GMT+0530
Current MomentA is: Tue Jan 31 2023 12:09:42 GMT+0530
Current MomentA is: Fri Jan 31 2025 12:09:42 GMT+0530

示例2:

const moment = require('moment'); 
  
let momentB = moment(); 
console.log( 
    "Current MomentB is:", momentB.toString() 
); 
  
momentB.subtract({ hours: 10, minutes: 50, seconds: 25 }); 
console.log( 
    "Current MomentB is:", momentB.toString() 
); 
  
let momentC = moment(); 
console.log( 
    "Current MomentC is:", momentC.toString() 
); 
  
momentC.subtract({ days: 10, months: 15, years: 2 }); 
console.log( 
    "Current MomentC is:", momentC.toString() 
);

输出:

Current MomentB is: Tue Jul 26 2022 01:24:42 GMT+0530
Current MomentB is: Tue Jul 26 2022 06:35:12 GMT+0530
Current MomentC is: Tue Jul 26 2022 01:24:42 GMT+0530
Current MomentC is: Mon May 31 2038 01:24:42 GMT+0530

参考: https://momentjs.com/docs/#/manipulating/subtract/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程