测试代码:
var c = moment().tz('America/New_York');
console.log('c.format: ' + c.format());
var b = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]).tz('America/Chicago');
console.log("b.format: " + b.format());
当我在本地运行此代码时,我得到:
c.format: 2017-07-03T16:33:42-04:00
b.format: 2017-07-03T16:33:00-05:00
这就是我期望(并且希望)发生的事情。基本上我只是想花点时间改变偏移量而不改变实际时间。但是,当我通过 Azure 托管应用程序运行相同的代码时,输出如下:
c.format: 2017-07-03T16:43:16-04:00
b.format: 2017-07-03T11:43:00-05:00
本地应用程序和 Azure 应用程序都运行相同的 Node 版本 (8.0.0)、时刻 (2.18.1) 和时刻时区 (0.5.13)。
有人知道这可能是什么原因造成的吗?谢谢!
最佳答案
作为docs说:
By default, moment parses and displays in local time.
对于您的 b
变量,您将使用 c.year()、c.month()、c.date()、c.hours()、c.minutes()
作为本地时间创建一个 moment 对象,因此将 b
转换为 America/Chicago
时区的结果将取决于系统。
您可以使用moment.tz
创建一个指定时区的时刻对象(例如 America/New_York
),在您的情况下,类似于:
moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York')
这里是显示不同情况下实时结果的片段:
// Current time in New York
var c = moment().tz('America/New_York');
console.log('c.format: ' + c.format());
// Create a local moment object for the current time in New York
var mLocal = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]);
console.log("mLocal.format: " + mLocal.format());
// Convert local moment to America/Chicago timezone
var b = mLocal.tz('America/Chicago');
console.log("b.format: " + b.format());
// Create moment object for the current time in New York
// specifying timezone and then converting to America/Chicago timezone
var b1 = moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York').tz('America/Chicago');
console.log("b1.format: " + b1.format());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>
关于javascript - 使用 momentjs,在本地与在 Azure 上获得不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44896097/