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

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

moment().duration().years() 方法用于获取持续时间的年数。该方法返回持续时间中完整的年数,因此返回一个整数作为值。

该方法与asYears()方法不同,asYears()方法返回给定持续时间的年数长度,可能有小数表示不完整的年份。

语法:

moment().duration().years();

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

返回值: 此方法返回持续时间的年数。

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

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

安装moment模块:

npm install moment

以下示例将演示 Moment.js moment.duration().years() 方法

示例1:

const moment = require('moment'); 
  
let durationOne = moment.duration(250, 'days'); 
let durationTwo = moment.duration(500, 'days'); 
  
// This returns 0 as the duration would 
// not even be a complete year 
console.log( 
  "durationOne years is:", durationOne.years() 
) 
  
// This returns 1 as the duration would be 
// more than 1 year, but less than 2 years 
console.log( 
  "durationTwo years is:", durationTwo.years() 
)

输出:

durationOne years is: 0
durationTwo years is: 1

示例2: 这个示例将帮助理解这个方法与asYears()的区别,以便更好地理解。

const moment = require('moment'); 
  
let durationA = moment.duration(65, 'weeks'); 
let durationB = moment.duration(256, 'weeks'); 
  
// The asYears() method will return a value 
// of the actual number of years of the duration 
console.log( 
  "Length of durationA in years is:", 
  durationA.asYears() 
) 
  
// The years() method will return the year 
// of the duration 
console.log("durationA years is:", durationA.years() 
) 
  
console.log( 
  "Length of durationB in years is:", durationB.asYears() 
) 
console.log("durationB years is:", durationB.years())

输出:

Length of durationA in years is: 1.2457476881797709
durationA years is: 1
Length of durationB in years is: 4.906329356523406
durationB years is: 4

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程