Moment.js moment.duration().months() 方法

Moment.js moment.duration().months() 方法

moment().duration().months() 方法用于获取持续时间的月份。该方法返回一个介于0和11之间的值。

该方法与 asMonths() 方法不同,后者返回给定持续时间的月数的长度。

语法:

moment().duration().months();

参数: 该方法不接受任何参数。

返回值: 该方法返回持续时间的月份(0-11)。

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

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

安装Moment模块:

npm install moment

下面的示例将演示 Moment.js moment.duration().months() 方法。

示例1:

const moment = require('moment'); 
  
// Example 1 
let durationOne = moment.duration(9, 'months'); 
let durationTwo = moment.duration(19, 'months'); 
  
// This returns 9 as it would be the 9th month 
// in the first year of the duration 
console.log( 
  "durationOne months is:", durationOne.months() 
) 
  
// This returns 7 as it would be the 7th month 
// in the second year of the duration 
console.log( 
  "durationTwo months is:", durationTwo.months() 
)

输出:

durationOne months is: 9
durationTwo months is: 7

示例2: 通过这个示例,可以更好地理解这种方法与asMonths()方法的区别。

const moment = require('moment'); 
  
let durationA = moment.duration(50, 'weeks'); 
let durationB = moment.duration(64, 'weeks'); 
  
// The asMonths() method will return a value 
// of the actual number of months of the duration 
console.log( 
  "Length of durationA in months is:", 
  durationA.asMonths() 
) 
  
// The months() method will return the 
// month of the duration 
// It can be denoted as floor(numberOfMonths % 12) 
console.log( 
  "durationA months is:", durationA.months() 
) 
  
console.log( 
  "Length of durationB in months is:", 
  durationB.asMonths() 
) 
console.log( 
  "durationB months is:", durationB.months() 
)

输出:

Length of durationA in months is: 11.499209429351732
durationA months is: 11
Length of durationB in months is: 14.718988069570218
durationB months is: 2

参考: https://momentjs.com/docs/#/durations/months/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程