问题描述
我试图根据所选时区转换日期.我很惊讶地看到时差为 5 分钟的日期的结果相同.例如,
I was trying to convert dates according to selected timezone. I was surprised to see same result for dates with 5 mins of time difference.For ex,
var x = "2017-07-10T18:30:00.000Z"
var y = "2017-07-10T18:35:00.000Z"
var z = "2017-07-10T18:45:00.000Z"
并尝试将它们转换为使用 moment.tz:
and tried converting them to using moment.tz:
moment.tz(x, 'America/New_York').format('DD/MM/YYYY HH:MM:SS');
moment.tz(y, 'America/New_York').format('DD/MM/YYYY HH:MM:SS')
moment.tz(z, 'America/New_York').format('DD/MM/YYYY HH:MM:SS')
令我惊讶的是,"10/07/2017 14:07:00"
的所有 3 个结果都相同.怎么了?任何帮助将不胜感激.
To my surprise, result was same for all 3 being "10/07/2017 14:07:00"
.What's going wrong? Any help will be appreciated.
推荐答案
简答:
问题是您使用大写 MM
(月份)而不是小写 mm
分钟 format()
.请注意,SS
(小数秒)和 ss
(秒)有同样的问题.
The issue is that you are using uppercase MM
(month) instead of lowercase mm
minutes in you format()
. Note that, you have the same problem for SS
(fractional seconds) and ss
(seconds).
关于您的代码示例的一般说明:
使用 moment.tz
用于使用给定时区解析时间字符串(例如 'America/New_York'
),moment.tz
不适用于将输入转换为给定时区.
Use moment.tz
for parsing time string using a given timezone (e.g. 'America/New_York'
), moment.tz
is not made for converting input to given timezone.
你必须使用 tz()
方法将时刻对象转换为给定时区.
You have to use tz()
method to convert a moment object to a given timezone.
请注意,您的输入字符串以 Z
结尾,因此它表示 UTC 时间.
Note that your input string ends with Z
so it represents time in UTC.
正如马特约翰逊在评论中指出的那样,在您的情况下,即使是 moment.tz(input, zone)
也会将输入转换为给定区域,因为输入字符串包含 Z
(保留 UTC 时区).无论如何,不鼓励这种方法.
As Matt Johnson pointed out in comments, in your case even moment.tz(input, zone)
would convert input to given zone because input string contains the Z
(that stays for UTC timezone). Anyway this kind of approach is discouraged.
这里的代码示例 解析 UTC 时间字符串并将其转换为 'America/New_York'
时区:
Here a code sample that parses UTC time string and converts it to 'America/New_York'
timezone:
var x = "2017-07-10T18:30:00.000Z";
var y = "2017-07-10T18:35:00.000Z";
var z = "2017-07-10T18:45:00.000Z";
console.log( moment.utc(x).tz('America/New_York').format('DD/MM/YYYY HH:MM:SS') );
console.log( moment.utc(y).tz( 'America/New_York').format('DD/MM/YYYY HH:mm:ss') );
console.log( moment.utc(z).tz( 'America/New_York').format('DD/MM/YYYY HH:mm:ss') );
<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>
这篇关于moment.tz 给出的结果不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!