2

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.

Corey
  • 107
  • 3
  • 10
  • 1
    Possible duplicate of [Convert date to another timezone in JavaScript](https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript) – Geshode Jan 16 '19 at 07:44
  • unclear question – amd Jan 16 '19 at 09:56

2 Answers2

1

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

moment.tz(moment(date), 'Asia/Tokyo').format('YYYY/MM/DD HH:MM Z')
clayton.carmo
  • 121
  • 1
  • 4
  • I'm sorry, but it return "2019/01/16 00:01 +09:00". It's a String and Minus maybe wrong. I want to return an Object like : Wed Jan 16 2019 00:00:00 GMT+0900 – Corey Jan 16 '19 at 08:15
0

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.

Sami Hult
  • 3,052
  • 1
  • 12
  • 17
  • I'm sorry, but it return "2019/01/16 00:01 +09:00". It's a String and Minus maybe wrong. I want to return an Object like : Wed Jan 16 2019 00:00:00 GMT+0900 – Corey Jan 16 '19 at 08:16
  • If you want a javascript `Date`, you should know it not fixed to any timezone. Unless you use more advanced models like `moment`, or do some conversion of your own, you can't then control the timezone. Formatting a `Date` object will output the time in *your computer's timezone*, in this case GMT-5. – Sami Hult Jan 16 '19 at 08:29
  • To focus on the solutions: If you need to express a date-time in Javascript in a specific timezone, don't use `Date`, it's too simple for that use. `moment` is a standard option, but alternatives exist. Use the `moment` objects instead of `Date`, in this case you could use `timezonedMoment` - it knows the timepoint and what timezone it's expected to work in. Same goes for Corey's simple `moment.tz(date, 'Asia/Tokyo')`. – Sami Hult Jan 16 '19 at 08:33
  • Yes, I know. But when I use new Date(date). It returned current timez_zone(-5). Not +9 as I expected. – Corey Jan 16 '19 at 09:35
  • @Corey The timezone in the string is used only for parsing. Dumping a `Date` object will yield the equivalent time and date in your current timezone. If you use `Date`, you will effectively lose timezone information. – Sami Hult Jan 16 '19 at 09:57