Need to format time zone offset using moment js

2020-07-22 16:17发布

I have a datepicker on my page, when I select any date it produced a result something like

Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)

And I need to format it: YYYY-MM-DDTHH:mm:ss Z

So, for this I use moment syntax

var date='Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)';
moment(date).format('YYYY-MM-DDTHH:mm:ss Z');

which produces an output

2014-09-07T00:00:00 +05:00

That's good, but my api expect standard timezone offset 'Z' instead of parsing into local current time zone (i.e +5:00) in my case.

So, I want to produce this

2014-09-07T00:00:00Z

How is it possible?

标签: momentjs
2条回答
欢心
2楼-- · 2020-07-22 16:52

Rather than using a hard-coded format string and then concatenating the 'Z' after it, it would be better to just use the toJSON() function which has been around since moment js v2.0. Like so:

moment('Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)').toJSON();

Here's the complete JSFiddle.

查看更多
虎瘦雄心在
3楼-- · 2020-07-22 16:53

Use moment.utc() to display time in UTC time instead of local time:

var dateValue = moment(date).utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';

or moment().toISOString() to display a string in ISO format (format: YYYY-MM-DDTHH:mm:ss.sssZ, the timezone is always UTC):

var dateValue = moment(date).toISOString();

JSFiddle

查看更多
登录 后发表回答