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

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

moment().set() 方法 用于将给定的时间单位设置到 Moment 对象中。该单位可以以所有识别的变体形式指定,包括其复数和简写形式。时间也可以使用包含所有所需时间单位的对象进行设置。

语法:

moment().set(String, Int)

或者

moment().set(Object(String, Int))

参数:

此方法接受如上所述的两个参数,并进行以下描述:

  • String:这是要设置为Moment对象的时间单位。

  • Int:这是要设置的时间值。

  • Object:也可以将时间指定为包含所有时间单位及其值的JSON对象。

返回值:

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

注意:

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

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

moment模块的安装:

npm install moment

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

示例1:

const moment = require('moment'); 
  
let momentOne = moment(); 
  
momentOne.set('year', 2010); 
momentOne.set('month', 6); 
momentOne.set('date', 10); 
  
console.log("MomentOne is:", momentOne.toString()); 
console.log("MomentOne year:", momentOne.year()); 
console.log("MomentOne month:", momentOne.month()); 
console.log("MomentOne date:", momentOne.date()); 
  
let momentTwo = moment(); 
  
momentTwo.set('y', 2022); 
momentTwo.set('m', 8); 
momentTwo.set('d', 19); 
  
console.log("MomentTwo is:", momentTwo.toString()); 
console.log("MomentTwo year:", momentTwo.year()); 
console.log("MomentTwo month:", momentTwo.month()); 
console.log("MomentTwo date:", momentTwo.date());

输出:

MomentOne is: Sat Jul 10 2010 00:28:08 GMT+0530
MomentOne year: 2010
MomentOne month: 6
MomentOne date: 10
MomentTwo is: Fri Aug 12 2022 00:08:08 GMT+0530
MomentTwo year: 2022
MomentTwo month: 7
MomentTwo date: 12

示例2:

const moment = require('moment'); 
  
let moment1 = moment(); 
  
moment1.set('hour', 10); 
moment1.set('minute', 18); 
moment1.set('second', 30); 
moment1.set('millisecond', 150); 
  
console.log( 
    "moment1 is:", 
    moment1.toString() 
); 
console.log( 
    "moment1 hour:", 
    moment1.hour() 
); 
console.log( 
    "moment1 minute:", 
    moment1.minute() 
); 
console.log( 
    "moment1 second:", 
    moment1.second() 
); 
console.log( 
    "moment1 millisecond:", 
    moment1.millisecond() 
); 
  
let moment2 = moment(); 
  
moment2.set('hour', 6); 
moment2.set('minute', 30); 
moment2.set('second', 10); 
moment2.set('millisecond', 3500); 
  
console.log( 
    "moment2 is:", 
    moment2.toString() 
); 
console.log( 
    "moment2 hour:", 
    moment2.hour() 
); 
console.log( 
    "moment2 minute:", 
    moment2.minute() 
); 
console.log( 
    "moment2 second:", 
    moment2.second() 
); 
console.log( 
    "moment2 millisecond:", 
    moment2.millisecond() 
);

输出:

moment1 is: Sun Jul 24 2022 10:18:30 GMT+0530
moment1 hour: 10
moment1 minute: 18
moment1 second: 30
moment1 millisecond: 150
moment2 is: Sun Jul 24 2022 06:30:13 GMT+0530
moment2 hour: 6
moment2 minute: 30
moment2 second: 13
moment2 millisecond: 500

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程