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

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

moment().get()方法 用于从Moment对象中获取给定的时间单位作为字符串。单位可以以所有可识别的形式进行指定,包括其复数形式和简短形式。它可以用于返回年、月、日、小时、分钟和毫秒的值。

语法:

moment().get( unit );

参数: 此方法接受一个参数,如上所述并以下面方式描述:

  • unit: 表示从Moment对象返回的时间单位的字符串。

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

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

moment.js可以使用以下命令进行安装:

安装moment模块:

npm install moment

以下示例将演示Moment.js的moment().get()方法。

示例1:

const moment = require('moment'); 
  
let momentOne = moment(); 
console.log( 
    "momentOne date:", momentOne.get('date') 
) 
console.log( 
    "momentOne month:", momentOne.get('month') 
) 
console.log( 
    "momentOne year:", momentOne.get('year') 
) 
  
let momentTwo =  
    moment() 
        .clone() 
        .add(8, 'days') 
        .add(5, 'months'); 
console.log( 
    "momentTwo date:", momentTwo.get('D') 
) 
console.log( 
    "momentTwo month:", momentTwo.get('M') 
) 
console.log( 
    "momentTwo year:", momentTwo.get('Y') 
)

输出:

momentOne date: 11
momentOne month: 6       
momentOne year: 2022     
momentTwo date: 19       
momentTwo month: 11      
momentTwo year: 2022     

示例2:

const moment = require('moment'); 
  
let momentA = moment(); 
console.log( 
    "momentA hours:", momentA.get('hour') 
) 
console.log( 
    "momentA minutes:", momentA.get('minute') 
) 
console.log( 
    "momentA seconds:", momentA.get('second') 
) 
console.log( 
    "momentA milliseconds:", momentA.get('millisecond') 
) 
  
let momentB = moment() 
                .clone() 
                .add(10, 'hours') 
                .add(100, 'millisecond'); 
console.log( 
    "momentB hours:", momentB.get('H') 
) 
console.log( 
    "momentB minutes:", momentB.get('m') 
) 
console.log( 
    "momentB seconds:", momentB.get('s') 
) 
console.log( 
    "momentB milliseconds:", momentB.get('ms') 
)

输出:

momentA hours: 1
momentA minutes: 54      
momentA seconds: 39      
momentA milliseconds: 237
momentB hours: 11
momentB minutes: 54
momentB seconds: 39
momentB milliseconds: 338

参考: https://momentjs.com/docs/#/get-set/get/

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程