node.js momentjs 将日期时间从另一个时区转换为 UTC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37534398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
momentjs convert datetime to UTC from another timezone
提问by KVISH
I'm having dates like the below:
我有如下日期:
05/30/2014 11:21:37 AM
2014 年 5 月 30 日上午 11:21:37
My users will be entering in that data and having their own timezone. It could be anything like "US/Eastern", "US/Pacific-New", etc. I want to convert the time to UTC but i'm not able to. Is there a way to do so?
我的用户将输入该数据并拥有自己的时区。它可以是“美国/东部”、“美国/太平洋-新”等。我想将时间转换为 UTC,但我不能。有没有办法这样做?
I'm using node and I tried momentJS and read the below:
我正在使用节点,我尝试了 momentJS 并阅读以下内容:
Convert date to another timezone in JavaScript
How do I convert from a different timezone to UTC?
如何从不同的时区转换为 UTC?
Edit
编辑
I have tried these:
我试过这些:
moment().utc(0).format('YYYY-MM-DD HH:mm Z')
moment.tz(dateString, "US/Eastern").format()
In the above example dateStringis the string date. I want to set the timezone to "US/Eastern" and convert it to UTC.
在上面的例子中dateString是字符串日期。我想将时区设置为“美国/东部”并将其转换为 UTC。
回答by Matt Johnson-Pint
// your inputs
var input = "05/30/2014 11:21:37 AM"
var fmt = "MM/DD/YYYY h:mm:ss A"; // must match the input
var zone = "America/New_York";
// construct a moment object
var m = moment.tz(input, fmt, zone);
// convert it to utc
m.utc();
// format it for output
var s = m.format(fmt) // result: "05/30/2014 3:21:37 PM"
Note that I used the same output format as input format - you could vary that if you like.
请注意,我使用了与输入格式相同的输出格式——如果你愿意,你可以改变它。
You can also do this all in one line if you prefer:
如果您愿意,也可以在一行中完成所有操作:
var s = moment.tz(input, fmt, zone).utc().format(fmt);
Additionally, note that I used the Area/Locality format (America/New_York), instead of the older US/Easternstyle. This should be prefered, as the US/* ones are just there for backwards compatibility purposes.
另外,请注意我使用了区域/区域格式 ( America/New_York),而不是旧US/Eastern样式。这应该是首选,因为 US/* 只是为了向后兼容的目的。
Also, US/Pacific-Newshould never be used. It is now just the same as US/Pacific, which both just point to America/Los_Angeles. For more on the history of this, see the tzdb sources.
此外,US/Pacific-New永远不应该使用。它现在和 一样US/Pacific,都只是指向America/Los_Angeles。有关此历史的更多信息,请参阅 tzdb 来源。

