I'm trying to parse a date created with moment.js, with a timezone obtained from an API response of this type:
{
"id": "MX",
"name": "Mexico",
"time_zone": "GMT-06:00"
}
I have a moment object created in react, but i need to change it's timezone to the one obtained by the API, in this example is "GMT-06:00".
For this i have this function:
setDateTimezone(date) {
let timezone = this.state.siteData.time_zone;
return moment(date).tz(timezone).format();
}
It receives a moment object and it changes it timezone with tz.
However, this returns the following error:
Moment Timezone has no data for GMT-06:00.
I need to somehow parse the API timezone format to one accepted by Moment, and create a new moment object with this new timezone.
Thanks a lot for your time, have a nice day.
I'm trying to parse a date created with moment.js, with a timezone obtained from an API response of this type:
{
"id": "MX",
"name": "Mexico",
"time_zone": "GMT-06:00"
}
I have a moment object created in react, but i need to change it's timezone to the one obtained by the API, in this example is "GMT-06:00".
For this i have this function:
setDateTimezone(date) {
let timezone = this.state.siteData.time_zone;
return moment(date).tz(timezone).format();
}
It receives a moment object and it changes it timezone with tz.
However, this returns the following error:
Moment Timezone has no data for GMT-06:00.
I need to somehow parse the API timezone format to one accepted by Moment, and create a new moment object with this new timezone.
Thanks a lot for your time, have a nice day.
Share Improve this question asked Feb 26, 2019 at 14:11 Rohr FacuRohr Facu 7371 gold badge13 silver badges33 bronze badges 1-
1
See moment-timezone docs: The
moment.tz
constructor takes all the same arguments as themoment
constructor, but uses the last argument as a time zone identifier.. SeeparseZone()
too. – VincenzoC Commented Feb 26, 2019 at 14:17
2 Answers
Reset to default 5You do not need moment-timezone for this. Just use the utcOffset
function from Moment. It will ignore the letters, so you can just do this:
moment(date).utcOffset('GMT-06:00').format()
In the perfect world, you have a region timezone identifier rather than a static TZ like the one you have, because these are not DST aware nor understand politics of time. If your only option it to work with GMTxy format then you can use Etc/GMTxy
, see the table below:
https://github./eggert/tz/blob/2017b/etcetera#L36-L42
And https://momentjs./timezone/docs/#/zone-object/offset/
So it would be something like:
const timezone = `Etc/GMT${parseInt(data.time_zone.replace(/GMT/, ''))}`
moment(date).tz(timezone).format()
(please note i haven't tested that thoroughly)