问题描述
我有这个后端,它会在设定的时区向我发送一个预先格式化的时间,但没有关于所述时区的任何信息.字符串如下:2013-08-26 16:55:00".
I have this backend that sends me a pre formatted time in a set time zone, but without any information for the said time zone. The strings are like: "2013-08-26 16:55:00".
我可以用这个字符串创建一个新的 moment.js 实例:
I can create a new moment.js instance with this string:
var time = moment("2013-08-26 16:55:00") //this creates time in my tz
但这只会在我自己的时区创建一个实例.
but this will only create an instance in my own time zone.
Moment.js 有一个插件,可以在特定时区创建对象的实例,效果很好,但我不能说我希望对象指向什么时间.
Moment.js have a plugin that can create instances of the object in specific time zones and it works great, but I can't say what time I want the object to point to.
如果我在纽约并且我这样做:
If I'm in New York and I do this:
var time = moment("2013-08-26 16:55:00").tz("America/Los_Angeles");
结果时间将是 13:55 而不是 16:55,但在洛杉矶.
the resulting time will be 13:55 instead of 16:55 but in LA.
我想要创建一个显示 16:55 但在洛杉矶时间的实例.
What I want is to create an instance that will say 16:55, but in LA time.
我问的原因是因为我想这样做:
The reason I'm asking is because I want to do this:
var now = moment.tz("America/Los_Angeles");
var end = moment("2013-08-26 16:55:00"); //plus something to convert LA time
var timeLeft = end.diff(now, "minutes");
有没有办法做到这一点?
Is there a way to do that?
推荐答案
在大多数情况下,您可以简单地这样做:
In most cases, you can simply do this:
moment.tz("2013-08-26 16:55:00", "America/Los_Angeles")
如果需要输入非ISO8601,则第二个参数指定格式字符串,第三个参数指定时区:
If you require input other than ISO8601, then specify the format string as the second parameter, and the time zone as the third:
moment.tz("8/26/2013 4:55 pm", "M/D/YYYY h:mm a", "America/Los_Angeles")
而如果你需要使用moment的严格解析"模式,则进入第三个参数,时区移动到第四个位置:
And if you need to use moment's "strict parsing" mode, then that goes in the third parameter, and the time zone moves to the fourth position:
moment.tz("8/26/2013 4:55 pm", "M/D/YYYY h:mm a", true, "America/Los_Angeles")
这篇关于如何使用 moment.js 在特定时区创建时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!