更改默认时区后如何在本地时间格式化时刻?

How do you format a moment in local time after changing the default timezone?

我有一个时间戳,我正在用 momentjs:

格式化它
moment("2015-03-24T09:47:31.042Z").format("LLL Z")
"March 24, 2015 10:47 AM +01:00"

由于我们应用程序的性质,我们 setting a default timezone for momentjs,这会影响所有渲染时刻:

moment.tz.setDefault("America/Los_Angeles")
moment("2015-03-24T09:47:31.042Z").format("LLL Z")
"March 24, 2015 2:47 AM -07:00"

到目前为止,太棒了。但是现在我想在应用程序的一个特定位置显示本地时间,但是 momentjs 当然会使用提供的默认时区:

moment().format("LLL Z")
"March 24, 2015 2:52 AM -07:00"

如何构造一个再次使用本地时区的 moment 实例?

我尝试使用 moment.tz(timestamp,null),但那只是使用 GMT。

感谢@Tanner 在评论中的建议和 Getting the client's timezone in JavaScript 中的答案,我才弄明白了。

您可以使用 utcOffset 设置时刻的 UTC 偏移量。结合Date.getTimezoneOffset,可以再次渲染当地时间:

moment("2015-03-24T09:47:31.042Z")
  .utcOffset(-new Date().getTimezoneOffset())
  .format("LLL Z")

"March 24, 2015 10:47 AM +01:00"