moment-timezone 格式没有 return 预期的结果
moment-timezone format doesn't return the expected result
使用 moment-timezone 中的 tz()
函数如下:
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').format()
//returns '2017-10-15T13:53:43+08:00'
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').format('h:m A')
//I expect to return '9:53 PM' but it returns '1:53 PM'
最终,我想应用fromNow()
函数来格式化结果。但是当我应用它时,它使用初始时间戳并忽略应用的时区。
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').fromNow()
//I expect to return '1 min ago' when actual time is 13:54 UTC (21:54 in HK) but it returns '8 hours ago'
我做错了什么?
当你这样做时:
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong');
您正在创建一个 date/time,它对应于 2017 年 10 月 15 日th,1:53 下午在香港 - 反过来对应于 2017-10-15T05:53:43Z
(5:53 AM in UTC)。
当您调用 format()
函数时:
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').format();
它returns:
2017-10-15T13:53:43+08:00
+08:00
部分就是 UTC offset - it just tells that Hong Kong is 8 hours ahead UTC。但是2017-10-15T13:53:43+08:00
(香港的1:53下午)与2017-10-15T05:53:43Z
(UTC 的5:53 AM)完全相同)。这就是为什么 fromNow()
,当当前时间是 13:54 UTC,returns 8 小时。
如果你想要date/time对应1:53 PM in UTC,你应该使用utc()
函数:
// October 15th 2017, 1:53 PM in UTC
moment.utc('2017-10-15 13:53:43');
现在,当当前时间是 13:54 UTC 时,fromNow()
将 return 1 分钟(因为 date/time 代表 1:53 UTC 下午).
要将其转换为香港时区,只需使用 tz()
函数:
// convert 1:53 PM UTC to Hong Kong timezone (9:53 PM)
moment.utc('2017-10-15 13:53:43').tz('Asia/Hong_Kong').format('h:m A');
这会将 1:53 PM UTC 转换为香港时区(导致 9:53 PM):
使用 moment-timezone 中的 tz()
函数如下:
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').format()
//returns '2017-10-15T13:53:43+08:00'
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').format('h:m A')
//I expect to return '9:53 PM' but it returns '1:53 PM'
最终,我想应用fromNow()
函数来格式化结果。但是当我应用它时,它使用初始时间戳并忽略应用的时区。
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').fromNow()
//I expect to return '1 min ago' when actual time is 13:54 UTC (21:54 in HK) but it returns '8 hours ago'
我做错了什么?
当你这样做时:
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong');
您正在创建一个 date/time,它对应于 2017 年 10 月 15 日th,1:53 下午在香港 - 反过来对应于 2017-10-15T05:53:43Z
(5:53 AM in UTC)。
当您调用 format()
函数时:
moment.tz('2017-10-15 13:53:43','Asia/Hong_Kong').format();
它returns:
2017-10-15T13:53:43+08:00
+08:00
部分就是 UTC offset - it just tells that Hong Kong is 8 hours ahead UTC。但是2017-10-15T13:53:43+08:00
(香港的1:53下午)与2017-10-15T05:53:43Z
(UTC 的5:53 AM)完全相同)。这就是为什么 fromNow()
,当当前时间是 13:54 UTC,returns 8 小时。
如果你想要date/time对应1:53 PM in UTC,你应该使用utc()
函数:
// October 15th 2017, 1:53 PM in UTC
moment.utc('2017-10-15 13:53:43');
现在,当当前时间是 13:54 UTC 时,fromNow()
将 return 1 分钟(因为 date/time 代表 1:53 UTC 下午).
要将其转换为香港时区,只需使用 tz()
函数:
// convert 1:53 PM UTC to Hong Kong timezone (9:53 PM)
moment.utc('2017-10-15 13:53:43').tz('Asia/Hong_Kong').format('h:m A');
这会将 1:53 PM UTC 转换为香港时区(导致 9:53 PM):