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

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

moment().duration().humanize()方法 用于以可读的格式返回持续时间的长度。默认情况下,返回的文本没有后缀,但是可以通过指定 withSuffix 参数来添加后缀。这也可以用于使用负持续时间表示过去的时间。

语法:

moment().duration().humanize(withSuffix, thresholds);

参数: 此方法接受上述提及的两个参数,并在下面进行了描述:

  • withSuffix: 这是一个布尔值,可用于指定返回的时间是否包含后缀。这是一个可选参数。
  • thresholds: 这是一个可选参数。

返回值: 此方法返回一个字符串,表示时间以人类可读的格式。

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

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

安装moment模块:

npm install moment

示例1: 下面的示例将演示 Moment.js moment.duration ().humanize () 方法

  • Filename: index.js
const moment = require('moment'); 
  
let durationOne = moment.duration(9, 'months') 
console.log( 
    "The humanized version of durationOne is:", 
    durationOne.humanize() 
); 
  
// Using the withSuffix property 
let durationTwo = moment.duration(5, 'hours') 
console.log( 
    "The humanized version of durationTwo is:", 
    durationTwo.humanize(true) 
);

运行应用程序的步骤: 在终端中输入下面的命令来运行index.js文件:

node index.js

输出:

The humanized version of durationOne is: 9 months
The humanized version of durationTwo is: in 5 hours

示例2:

const moment = require('moment'); 
  
// Changing of locale 
let durationThree =  
    moment.duration(9, 'months').locale('es'); 
console.log( 
    "The humanized version of durationThree is:", 
    durationThree.humanize() 
); 
  
// Changing of locale with suffix 
let durationFour =  
    moment.duration(9, 'months').locale('es'); 
console.log( 
    "The humanized version of durationFour is:", 
    durationFour.humanize() 
); 
  
// Using a negative duration 
let durationFive =  
    moment.duration(-5, 'days') 
console.log( 
    "The humanized version of durationFive is:", 
    durationFive.humanize(true) 
);

输出:

The humanized version of durationThree is: 9 meses
The humanized version of durationFour is: 9 meses
The humanized version of durationFive is: 5 days ago

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程