Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

javascript - How to create time in a specific time zone with moment.js

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

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

the resulting time will be 13:55 instead of 16:55 but in 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");

Is there a way to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In most cases, you can simply do this:

moment.tz("2013-08-26 16:55:00", "America/Los_Angeles")

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...