最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Moment.jsmoment-timezone: Format date with 'GMT-06:00' type date - Stack Overflow

programmeradmin1浏览0评论

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 the moment constructor, but uses the last argument as a time zone identifier.. See parseZone() too. – VincenzoC Commented Feb 26, 2019 at 14:17
Add a ment  | 

2 Answers 2

Reset to default 5

You 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)

发布评论

评论列表(0)

  1. 暂无评论