javascript - 如何使用开放天气 API 获取搜索城市的实时本地日期和时间

标签 javascript openweathermap weather-api

我使用开放天气 API 创建了一个天气项目:https://openweathermap.org/current?fbclid=IwAR1SVc9zn9uXaZWLmJA9lYEeZvUc1s_kR68RFadWuIwd8yBjIyJ7zsVMKkE
我已将所有 API 参数添加到我的代码中。
但是,我也想获取 直播正在搜索的城市的本地日期和时间。
例如,当用户搜索“雅典”时,它会显示如下内容:

Saturday 15/1/2022 16:24:03 (I want the seconds to change live every second that passes)


我的代码:
javascript 和 HTML 脚本插入

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 { lon } = data.coord;
    const { lat } = data.coord;
    const { icon, description } = data.weather[0];
    const { feels_like } = data.main;
    const { temp, humidity } = data.main;
    const {temp_min} = data.main;
    const {temp_max} = data.main;
    const { pressure } = data.main;
    const { speed } = data.wind;
    const { deg } = data.wind;
    const { visibility } = data;
    const { all } = data.clouds;
    const { gust } = data.wind;
    const {timezone} = data;
    const { sunrise } = data.sys;
    const { sunset } = data.sys;

  
//Displaying the results:
    document.querySelector(".city").innerText = "Weather: " + name;
    document.querySelector(".lon").innerText = "Longitude: " + lon;
    document.querySelector(".lat").innerText = "Latitude: " + lat;
    document.querySelector(".icon").src =
      "https://openweathermap.org/img/wn/" + icon + ".png";
    document.querySelector(".description").innerText = description;
    document.querySelector(".temp").innerText = temp + "°C";
    document.querySelector(".feels-like").innerText = "Temperature feels like: " + feels_like + "°C";
    document.querySelector(".temp_min").innerText = "Minimum Temperature: " + temp_min + "°C";
    document.querySelector(".temp_max").innerText = "Maximum Temperature: " + temp_max + "°C";
    document.querySelector(".humidity").innerText =
      "Humidity: " + humidity + "%";
    document.querySelector(".visibility").innerText = "Visibility: " + visibility + " meters";
    document.querySelector(".cloudiness").innerText = "Cloudiness: " + all + "%";
    document.querySelector(".pressure").innerText = "Atmospheric Pressure: " + pressure + " hPa";
    document.querySelector(".wind").innerText =
      "Wind speed: " + speed + " km/h";
    document.querySelector(".wind-deg").innerText = "Wind degrees: " + deg + "°";
    document.querySelector(".wind-gust").innerText = "Wind gust: " + gust + " m/s";
    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 weather on page load
weather.fetchWeather("Athens");
<script src="https://momentjs.com/downloads/moment.js"></script>
 <!-- script to convert sunrise and sunset times to time format and on the local time of the searched city -->
 <script src="./script.js" defer></script>
 <!-- local script -->

我应该对我的代码做哪些修改?
注意:如果可能的话,我想要 LIVE 日期和时间。

最佳答案

你可以试试Time API
使用此 API,您可以 获取当前时间地球上任何位置的时区信息 , 转换时区并列出 所有夏令时 (DST) 更改 在特定位置。

根据文档(使用 cURL 实现):

$ ACCESSKEY="<Your Access Key>"
$ SECRETKEY="<Your Secret Key>"
$ curl -G \
    --data-urlencode "version=3" \
    --data-urlencode "prettyprint=1" \
    --data-urlencode "accesskey=$ACCESSKEY" \
    --data-urlencode "secretkey=$SECRETKEY" \
    --data-urlencode "placeid=norway/oslo" \
    https://api.xmltime.com/timeservice

关于javascript - 如何使用开放天气 API 获取搜索城市的实时本地日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70722396/

相关文章:

javascript - simpleweatherjs js 插件不更新新的天气温度而是返回 [object object]

swift - iOS - UI 标签未更新

javascript - openweathermap api 在 IE11 中不工作

javascript - 无法用 RegExp 替换 UTF-8 字符

javascript - 在 AngularJS 和 Jade 中使用无限滚动

javascript - ReactJS:无法将 api 响应渲染到 h2 标签中,但可以将其记录到控制台

php - OpenWeatherMap API 生成不正确的输出

c# - javascript切换背景图片

javascript - React JSX - 以粗体显示子字符串

c++ - (C++) 使用天气 API