Create new Date object by using moment.js

Viewed 4516

I have string:

date =  "2019/1/16 00:00 +0900"

I'm in New York (timezone -5), I want to create an Date object like that:

Wed Jan 16 2019 00:00:00 GMT+0900

I can't use javascript to convert. It will return with timezone -5. I use moment.js:

moment.tz(date, 'Asia/Tokyo').format('YYYY/MM/DD HH:MM');

However, it's not right. Could you please help me. Thank a lot.

2 Answers

It will work if your date object is a moment instance:

moment.tz(moment(date), 'Asia/Tokyo').format('YYYY/MM/DD HH:MM Z')

Timezones are difficult to get right. I think an easy-to-follow and somewhat idiomatic solution is this:

const date = "2019/1/16 00:00 +0900";

// parse in any timezone
const dateMoment = moment(date); 

// deliberately set the timezone in which the moment is interpreted in
const timezonedMoment = dateMoment.tz('Asia/Tokyo'); 

// format the moment
const formattedDate = dateMoment.format('YYYY/MM/DD HH:MM z');

Of course, you would write this in a more concise form.

Related