如何使用moment.js在特定时区中创建时间 [英] How to create time in a specific time zone with moment.js

查看:379
本文介绍了如何使用moment.js在特定时区中创建时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个后端,它在设定的时区中向我发送了一个预格式化的时间,但是没有关于所述时区的任何信息.字符串就像:"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,但在LA时间.

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");

有办法吗?

推荐答案

在大多数情况下,您可以简单地执行以下操作:

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")

如果您需要使用矩的严格解析"模式,则将其输入第三个参数,并将时区移至第四个位置:

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在特定时区中创建时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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