Search code examples
javascriptweather-api

How to display sunrise and sunset time in the local time of the city that is being searched


I have created a project that displays the sunrise and sunset by searching the name of the city. I use the open weather API.

However, when I search for a city with different timezone than my country (Greece), it converts the sunrise-sunset times to Greece's local timezone.

For example, I search "Albania"

enter image description here

The sunrise and sunset times in Albania are displayed in Greece's timezone. (Note: Greece is 1 hour ahead of Albania)

enter image description here

Normally, the sunrise-sunset times in Albania are: 7:02 AM and 4:35 PM.

However, it displays 8:02 and 17:35 which are 1 hour ahead of the normal sunrise-sunset times because they are converted to Greece's local timezone.

MY CODE

let weather = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXX",
  fetchWeather: function (city) {
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
        city +
        "&units=metric&lang=en&appid=" +
        this.apiKey
    )
  
      .then((response) => {
        if (!response.ok) {
          alert("No weather found.");
          throw new Error("No weather found.");
        }
        return response.json();
      })
      .then((data) => this.displayWeather(data));
  },
  
  //fetching the API parameters:
  displayWeather: function (data) {
    const { name } = data;
    const { sunrise } = data.sys;
    const { sunset } = data.sys;

  
//Displaying the results:
    document.querySelector(".city").innerText = "Weather: " + name;
    document.querySelector(".sunrise").innerText = "Sunrise: " + window.moment(sunrise * 1000).format('HH:mm a');
    document.querySelector(".sunset").innerText = "Sunset: " + window.moment(sunset * 1000).format('HH:mm a');
    document.querySelector(".weather").classList.remove("loading");
    document.body.style.backgroundImage =
      "url('https://source.unsplash.com/1600x900/?')"; 
  },

  
  search: function () {
    this.fetchWeather(document.querySelector(".search-bar").value);
  },
};

document.querySelector(".search button").addEventListener("click", function () {
  weather.search();
});

document
  .querySelector(".search-bar")
  .addEventListener("keyup", function (event) {
    if (event.key == "Enter") {
      weather.search();
    }
  });
//Displaying Athens sunrise sunset on page load
weather.fetchWeather("Athens");

I want it to display the normal sunrise-sunset local time for each city without them displaying in Greece's timezone.

Can anyone help me? I am begginer so I would appreciate if you could elaborate on your answer.


Solution

  • In your API response you will receive a timezone attribute which is in seconds (positive/negative). You can extract that from there. I converted the UNIX timestamp to UTC and added the timezone.

    Here is sunrise time for Tirana Albania

    let timezone = 3600;
    let sunrise = 1642226661;
    
    let x = moment.utc(sunrise,'X').add(timezone,'seconds').format('HH:mm a');
    
    console.log(x);
    <script src="https://momentjs.com/downloads/moment.js"></script>