在 moment.js 中格式化日期时如何保留时区?

Nag*_*Nag 7 javascript momentjs

我有一个像这样的日期2015-10-24T17:12-05:00,我正在使用 moment.js 将其格式化,如下所示:

moment('2015-10-24T17:12-05:00').format('h:mm A');
Run Code Online (Sandbox Code Playgroud)

moment.js 似乎没有显示字符串中指定的时区的时间,而是将其转换为我计算机的时区。格式化时如何保留时区?

小智 3

var estTime = '2019-09-01T14:30:00-04:00';
var istTime = "2019-10-01T23:20:00+05:30";
console.log(estTime , "  ", moment(estTime).format("hh:mm") ," ", moment.parseZone(estTime).format("hh:mm"));
console.log(istTime, "  ", moment(istTime).format("hh:mm"), " ", moment.parseZone(istTime).format("hh:mm"));
Run Code Online (Sandbox Code Playgroud)

Moment 的字符串解析函数类似于moment(string)moment.utc(string)接受偏移量信息(如果提供),但将生成的 Moment 对象转换为本地或 UTC 时间。相反,moment.parseZone()解析字符串,但将生成的 Moment 对象保留在固定偏移时区中,并在字符串中提供偏移量。

解析区

输出:

2019-09-01T14:30:00-04:00 02:30 02:30

2019-10-01T23:20:00+05:30 01:50 11:20