使用节点 js 从时区获取时间

Get time from time zone using node js

本文关键字:时区 获取 取时间 js 节点      更新时间:2023-09-26

我需要使用节点JS从时区打印实际时间。

这是我的代码

var moment = require('moment-timezone');
console.log(moment().tz("UTC+05:30").format());
console.log(moment().tz("UTC+05").format());
console.log(moment().tz("UTC−04:30").format());
console.log(moment().tz("UTC+08").format());
console.log(moment().tz("UTC+06").format());

但我得到了这样的结果

Moment Timezone has no data for UTC+05:30. See http://momentjs.com/timezone/docs/#/data-loading/.
2016-03-09T16:31:10+05:30
Moment Timezone has no data for UTC+05. See http://momentjs.com/timezone/docs/#/data-loading/.
2016-03-09T16:31:10+05:30
Moment Timezone has no data for UTC−04:30. See http://momentjs.com/timezone/docs/#/data-loading/.
2016-03-09T16:31:10+05:30
Moment Timezone has no data for UTC+08. See http://momentjs.com/timezone/docs/#/data-loading/.
2016-03-09T16:31:10+05:30
Moment Timezone has no data for UTC+06. See http://momentjs.com/timezone/docs/#/data-loading/.
2016-03-09T16:31:10+05:30

如何解决这个问题?

如文档中所述,moment.tz([string])希望[string]采用'Country/City'格式,并且不接受UTC+XX格式。

使用 moment().utcOffset([string]) 在格式化之前应用 UTC 偏移量。

按照您的问题,您可以使用:

moment().utcOffset(520).format() // for UTC+5:30