【问题标题】:How to get a date from a timeZone (Moment Timezone)?如何从时区(时刻时区)获取日期?
【发布时间】:2025-12-14 06:25:01
【问题描述】:

即使Moment Timezone documentation 相当不错,我也遇到了问题。如何简单地获取时区日期?

在 IOS 应用上,我需要从时区获取日期,但与运行我的应用的系统无关。

基本上,如果我的应用在美国使用,我希望能够立即实时获得“欧洲/巴黎”日期()。

这可以使用 Moment Timezone 吗?

// This line is giving me the smartphone's system date
var today = moment().tz('Europe/Paris');
console.log(today.format());

// This line is giving me the smartphone's system date less one hour
var today2 = moment().tz('Etc/GMT-1');
console.log(today2.format());

// I have no clue where this date is coming from, it doesn't related to my system hour
var today3 = moment().tz('America/Los_Angeles');
console.log(today3.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.21/moment-timezone-with-data-2012-2022.min.js"></script>

【问题讨论】:

  • 你看到的结果都是正确的。您获得的时间是这些时区的当前时间。
  • 是的,我知道这应该是正确的,但是当我手动更改智能手机的小时数时,它也会使用 Moment().tz() 更改这些结果...
  • “手动更改智能手机的小时”是什么意思?如果您将时间设置为错误值,您的手机以及您的代码将不知道正确的时间。
  • 示例:法国现在是下午 6:49。所以我希望我的var today = moment().tz('Europe/Paris'); 给我:Sun Jul 01 2018 06:49:00 GMT+0200。为了验证这是否给了我正确的答案,我正在修改智能手机的时钟并测试我的应用程序。因为我不想要与智能手机系统时钟相关的结果。我更清楚了吗?

标签: javascript datetime momentjs


【解决方案1】:
let today = moment().tz("America/Los_Angeles")

这应该通过调用 moment() 获取当前日期并使用 tz 更改时区。 See docs here.

对于调试,请尝试以下方式:moment.tz 接受日期和将日期更改为的 tz。

let now = moment()
console.log(now)
let nowTZ = moment.tz(now, "America/Los_Angeles");
console.log(nowTZ)

【讨论】:

  • 这正是我尝试过的,但它不起作用......当我手动更改智能手机的时间时,它也会使用 Moment().tz() 更改这些结果。跨度>
  • 我添加了一种不同的方法来帮助调试它 - 我更新的答案中两个 console.log 语句的输出是什么?
  • Arf,我想如果不参考使用Moment Timezone 的系统时钟,就不可能从不同的时区获取日期。从第一个console.log() 开始,我正在获取智能手机的时钟时间。在第二个中,它是根据我的智能手机时钟时间计算的洛杉矶时间。