MomentJS时区返回错误的日期和时间 [英] MomentJS Timezone is returning incorrect date and time

查看:223
本文介绍了MomentJS时区返回错误的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用moment.js和moment-timezone-with-data.min.js来计算日期时间.

I am using moment.js and moment-timezone-with-data.min.js to calculate the date time.

我使用的日期/时间如下:

The date / time I am using is as follows:

var dGC2018 = moment('2018-04-04T18:00:00').tz("Australia/Queensland");

日期是2018年4月4日.时间是6PM.时区是昆士兰州.

The date is 4th of April 2018. The time is 6PM. The timezone is Queensland.

输出(使用console.log)是:

The output (using console.log) is:

Thu Apr 05 2018 04:00:00 GMT+1000 (E. Australia Standard Time) {}

可以通过将dCG2018输出到console.log并扩展返回的对象以找到_d属性来找到此输出.

This output can be found by outputting dCG2018 to the console.log and expanding the returned object to find the _d property.

为什么momentjs相对于我的输入参数说明了错误的日期/时间?

Why is momentjs stating the incorrect date / time relative to my input parameters?

推荐答案

您必须使用 tz 函数. moment.tz 使用给定的时区(在您的情况下为'Australia/Queensland').

由于使用本地时区解析字符串(如所述 :默认情况下,矩会解析并以当地时间显示.),然后将其转换为'Australia/Queensland'时区.

You are getting the wrong output because you are parsing a string using local timezone (as stated here: By default, moment parses and displays in local time.) and then converting it to 'Australia/Queensland' timezone.

此外,您不必使用_d和其他内部属性即可获取矩对象的值.如momentjs官方指南的内部属性部分所述:

Moreover, you do not have to use _d and other internal propertries to get the value of moment objects. As stated in the Internal Properties section of momentjs official guide:

Moment对象具有几个内部属性,这些属性以_为前缀.

最常查看的内部属性是_d属性,其中包含Moment包装器的JavaScript Date.通常,开发人员会对控制台输出_d的值感到困惑. Moment使用了一种称为时代转移的技术,该技术有时会导致此属性与Moment反映的实际日期值不同.特别是,如果正在使用Moment TimeZone,则此属性几乎永远不会与Moment从其公共.format()函数输出的实际值相同.因此,_d的值和任何其他带有_前缀的属性均不得用于任何目的.

The most commonly viewed internal property is the _d property that holds the JavaScript Date that Moment wrappers. Frequently, developers are confused by console output of the value of _d. Moment uses a technique called epoch shifting that causes this property to sometimes differ from the actual date value that the Moment reflects. In particular if Moment TimeZone is in use, this property will almost never be the same as the actual value that Moment will output from its public .format() function. As such, the values of _d and any other properties prefixed with _ should not be used for any purpose.

要打印出Moment的值,请使用.format().toString().toISOString().

To print out the value of a Moment, use .format(), .toString() or .toISOString().

这里是一个工作示例:

var dGC2018 = moment.tz('2018-04-04T18:00:00', "Australia/Queensland");
console.log(dGC2018.format())

<script src="https://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>

这篇关于MomentJS时区返回错误的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆