如何使用moment-tz.js解析tz,如“GMT-08:00”。 [英] How to use moment-tz.js to parse tz like "GMT-08:00"

查看:1069
本文介绍了如何使用moment-tz.js解析tz,如“GMT-08:00”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试运行此js

return function(milliSeconds, timeZoneId) {
    if (milliSeconds == 0) {
        return "";
    }
    var now = moment();

    return now.tz(timeZoneIdm, milliSeconds).format('MMM d, yyyy H:mm:ss'); 
}

例如使用此输入:

milliSeconds = "1524578400000"

timezoneId = "GMT-08:00"

解析GMT-08:00时失败。无论如何我可以调整它吗?

it fails for parsing "GMT-08:00". Anyway can I adjust it to work?

推荐答案

as moment.tz(...,String) docs states :

As moment.tz(..., String) docs states:


moment.tz构造函数采用与时刻相同的参数构造函数,但使用最后一个参数作为时区标识符

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

时区标识符类似于'America / New_York''Europe / Rome'GMT-08:00不是有效输入。

A time zone identifier is something like 'America/New_York' or 'Europe/Rome', "GMT-08:00" is not a valid input.

在您的情况下,您可以使用 时刻(数字) 然后:

In your case you can use moment(Number) and then:

  • converting to given zone using tz() function
  • or set offset using utcOffset(String)

var milliSeconds = "1524578400000";
var timezoneId = "GMT-08:00";

var timeInt = parseInt(milliSeconds, 10)
var m1 = moment(timeInt).tz('America/Los_Angeles');
console.log(m1.format('MMM D, YYYY H:mm:ss'));

var offset = timezoneId.substring(3);
var m2 = moment(timeInt).utcOffset(offset);
console.log(m2.format('MMM D, YYYY H:mm:ss'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>

请注意:


  • 时刻格式标记区分大小写,因此您必须使用 YYYY 多年, D 为月份( d 是星期几)

  • 1524578400000 2018-04-24 14:00:00 UTC,我很想念为什么你期望早上5点作为输出。

  • moment formatting tokens are case sensitive, so you have to use YYYY for years and D for day of the month (d is day of the week)
  • 1524578400000 is 2018-04-24 14:00:00 UTC, I'm missing why you are expecting 5am as output.

这篇关于如何使用moment-tz.js解析tz,如“GMT-08:00”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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