0

Small problem that's driving me nuts. I'm getting a time as a string from an API call, and I'm getting the timezone the time is in, as two separate strings. I'm trying to create a moment that is using this given data and it's taking my local machine timezone as a starting point and adjusting into the given zone

let timeFromApi = "01 Jan 2021 15:00";             //That's 3pm, Eastern Standard Time
let timeZoneFromApi = "America/Indianapolis";     //Server says "time I gave is in EST"

If I do either of these, with my local machine set to UTC:

let x = moment.tz(timeFromApi, timeZoneFromApi).format("YYYY-MM-DDTHH:mm:ss zz");
let y = moment(timeFromApi).tz(timeZoneFromApi).format("YYYY-MM-DDTHH:mm:ss zz");

Then they both end up containing "2021-01-01 10:00 -05"..

Moment seems to assume the given string is in timezone the local machine is in: If I set the local machine to EST, then I get "2021-01-01 15:00 -05" like I expect...

... but I don't want moment reading the local machine time at all. I literally want to give it a time, and give it a timezone and have it create that time in that timezone - how do I do this?

Caius Jard
  • 72,509
  • 5
  • 49
  • 80

1 Answers1

1

Having gone through the same sort of trouble, I can tell you that

let x = moment.tz(timeFromApi, timeZoneFromApi);

is the correct method. The documentation also says that is the way to do. I suspect your trouble is the formatting not the parsing. The z and zz formatting options are deprecated as of 1.6 (see https://momentjs.com/docs/#/displaying/). So I'd play with the formatting a bit.

Corin
  • 2,317
  • 2
  • 32
  • 47