Moment.js moment().utc() 方法
moment().utc() 方法 用于指定给定Moment对象的时区显示为UTC。可以传递一个可选参数,该参数保持当前时间值,只更改时区为UTC。
语法:
moment().utc( Boolean );
参数: 该方法接受一个单一参数,如上所述并如下所述:
- Boolean: 它是一个布尔值,指定是否更改时区,而不更改实际时间本身。
返回值: 该方法返回具有新时区的 Moment 对象。
注意: 这在正常的Node.js程序中不起作用,因为它需要全局或项目目录中安装外部的moment.js库。
可以使用以下命令安装Moment.js:
Moment模块的安装:
npm install moment
以下示例将演示Moment.js的moment().utc()
方法。
示例1:
const moment = require('moment');
let momentOne = moment();
console.log(
"MomentOne is:", momentOne.toString()
);
console.log(
"MomentOne hours:", momentOne.hours())
;
console.log(
"MomentOne minutes:", momentOne.minutes()
);
// Display utc format of the Moment
momentOne.utc()
console.log(
"MomentOne is:", momentOne.toString()
);
console.log(
"MomentOne hours in UTC:", momentOne.hours()
);
console.log(
"MomentOne minutes in UTC:", momentOne.minutes()
);
输出:
MomentOne is: Sun Jul 24 2022 01:42:42 GMT+0530
MomentOne hours: 1
MomentOne minutes: 42
MomentOne is: Sat Jul 23 2022 20:12:42 GMT+0000
MomentOne hours in UTC: 20
MomentOne minutes in UTC: 12
示例2:
const moment = require('moment');
let momentTwo = moment();
console.log(
"MomentTwo is:", momentTwo.toString()
);
console.log(
"MomentTwo hours:", momentTwo.hours())
;
console.log(
"MomentTwo minutes:", momentTwo.minutes()
);
// Change the timezone flag, without changing the time
// by passing the Boolean value to true
momentTwo.utc(true)
console.log(
"MomentTwo is:", momentTwo.toString()
);
console.log(
"MomentTwo hours in UTC:", momentTwo.hours()
);
console.log(
"MomentTwo minutes in UTC:", momentTwo.minutes()
);
输出:
MomentTwo is: Sun Jul 24 2022 01:42:42 GMT+0530
MomentTwo hours: 1
MomentTwo minutes: 42
MomentTwo is: Sun Jul 24 2022 01:42:42 GMT+0000
MomentTwo hours in UTC: 1
MomentTwo minutes in UTC: 42
参考: https://momentjs.com/docs/#/manipulating/utc/