使用 moment timezone js 将日期字符串转换为带时区的日期

Convert date string to date with timezone using moment timezone js

我需要将日期字符串转换为 PDT(太平洋夏令时),并且结果日期时间必须以本地时间显示。

我试过

console.log(moment.tz("16:23:42 Sep 27, 2018 PDT", 'HH:mm:ss MMM DD, YYYY PDT',"PDT").format());

当我 运行 上面的代码显示

2018-09-27T16:23:42Z

这不是当地时间。与其等效的本地时间必须不同。如何获取指定日期字符串的本地时间。

换句话说,我的意思是这样说https://forums.asp.net/t/1552114.aspx?Convert+Datetime+String+from+PDT+to+IST+local+time+datetime+string

你可以试试这个,我认为它会起作用

首先获取时区偏移量 timeZoneId 是您的时区。

const offset =  moment['tz'](moment(new Date()), timeZoneId).utcOffset() * 60000;

其次根据您的日期和偏移量创建新日期

console.log(new Date(new Date(yourDateString).getTime() + offset))

是的,yourDateString 是您的日期字符串,更适合日期对象,但是 w/e

你可以这样做:

var desiredFormat = "HH:mm:ss MMM DD, YYYY";
var timeToBeConverted = moment("16:23:42 Sep 27, 2018", desiredFormat);
var timeZone = "America/Los_Angeles";

console.log(timeToBeConverted.tz(timeZone).format(desiredFormat) + " PDT");

您提供的时区不能是"PDT"。如果您在控制台中使用 moment.tz.names(),您将获得有效时区名称的列表。在上面的示例中,我使用了 "America/Los_Angeles",但任何观察 PDT 的区域都可以。