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
495 views
in Technique[技术] by (71.8m points)

javascript - JSON date, display original date in the server's timezone

For example, I have a string date like this (I'm getting this from the server in json, from rails app)

s = "2013-09-01T00:00:00.000+08:00"

I would like to display it like so

01.09.2013

So I'm using moment.js library for this

moment(s).zone("+08:00").format("DD.MM.YYYY")
>> "01.09.2013"

But I don't know if needed timezone is +08:00. If I skip .zone() call, result would be wrong because my browser is in differnt timezone

moment(s).format("DD.MM.YYYY")
>"31.08.2013"

Even though in my original string I had +08:00 at the end.

So, my question is how can I extract time zone from json date string using pure javascript or moment.js library?

The simplest way I can think of is extracting the last 6 characters manually,

s.slice(s.length - 6, s.length)
> "+08:00"

But maybe there is a better approach for this task?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Just use the parseZone function, like so:

moment.parseZone(s)

Documentation is here.

Alternatively, you can use the older approach, which does the same thing:

moment(s).zone(s)

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

1.4m articles

1.4m replys

5 comments

56.8k users

...