Espskully
Espskully

Reputation: 107

API sunrise/sunset - convert from UTC to local time

I have this in my JavaScript:

fetch("https://api.sunrise-sunset.org/json?lat=51.2694&lng=-113.9804")
.then(res => res.json())
.then(data => {
    sunrise.innerHTML = `Sunrise: ${data.results.sunrise}`
    sunset.innerHTML = `Sunset: ${data.results.sunset}`
})

It returns the data in UTC. How can I convert it to my local time (MST)?

Upvotes: 0

Views: 1672

Answers (1)

Bravo
Bravo

Reputation: 6263

If you add &formatted=0 to your request, you get the unformatted date - then you can use new Date - which makes it simple

fetch("https://api.sunrise-sunset.org/json?lat=51.2694&lng=-113.9804&formatted=0")
  .then(res => res.json())
  .then(data => {
    const sunrise = new Date(data.results.sunrise);
    console.log(data.results.sunrise);
    console.log(sunrise.toString());
  });

Upvotes: 1

Related Questions