ivan milenkovic
ivan milenkovic

Reputation: 101

Openweather API, time always in my local time zone

I am including data from Openweather API which returns this, among other things:

dt: 1583876444
sys:
   country: "ES"
   sunrise: 1583822046
   sunset: 1583864165
timezone: 3600

My solution for timezone was to divide this number with 3600:

`Timezone: GMT ${data.timezone / 3600}:00 `

This somehow works and I get for example 'Timezone: GMT 9:00' although for some places like Tehran I get 'Timezone: GMT 3.5:00' and it is not ideal obviously. Any better solution for this?

For sunrise/sunset, I did this:

let date = new Date(data.sys.sunrise * 1000).toString();
  let sunrise = date.slice(16, 24);
...
`<h1>${sunrise}</h1>`

And I get what I want, like 03:50:36

Problem is it is always my local time, it shows me when sunrises in Tokyo but in my local time and not in Tokyo's local time. Obviously I would like to get Tokyo's local time. Is this doable?

Upvotes: 0

Views: 8699

Answers (2)

G-8
G-8

Reputation: 107

I faced the exact same problem with openweather. Add the timezone to the time and then times by 1000.

for sunrise/sunset:

const sunrise = new Date((data.sys.sunrise + data.timezone) * 1000)

You will get the local time

Upvotes: 7

Dave Pastor
Dave Pastor

Reputation: 241

I would strongly recommend you to use Moment: https://momentjs.com/timezone/ is a solid library and user tested.

Hope that helps.

Upvotes: 0

Related Questions