BegCoder
BegCoder

Reputation: 103

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.

Upvotes: 0

Views: 6883

Answers (2)

user22317667
user22317667

Reputation: 1

I solved this problem by getting timezone offset of the browser in seconds and adding it to the timestamp and the timezone offset of the timestamp location to get the time in the timezone of the location instead of the browser timezone.

function readTimeStamp(unixTimestamp: number, timezoneOffset: number) {
    const clientOffset = new Date().getTimezoneOffset();
    const offsetTimestamp = (unixTimestamp + (clientOffset * 60) + timezoneOffset)
    var date = new Date(offsetTimestamp * 1000);

    return date.toLocaleTimeString();
  }

Upvotes: 0

cmgchess
cmgchess

Reputation: 10297

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>

Upvotes: 2

Related Questions