显示日期名称,而不是Open Weather API响应中的数字

时间:2019-05-10 04:42:30

标签: javascript json openweathermap

我正在与Open Weather API一起玩,设法显示3天的天气,但是我不知道如何显示日期,而不是该数字!

进行搜索后,我发现我必须将时间戳记转换为正常时间:/,但我听不懂。

$(document).ready(function() {
  var key = "16c772c85cc7406ce72731159d78b31b";
  var city = "Pune,IN";
  var url = "https://api.openweathermap.org/data/2.5/forecast";
  $.ajax({
    url: url, //API Call
    dataType: "json",
    type: "GET",
    data: {
      q: city,
      appid: key,
      units: "metric",
      cnt: "3"
    },
    success: function(data) {
      console.log('Received data:', data) // For testing
      var wf = "";
      wf += "<h2>" + data.city.name + "</h2>"; // City (displays once)
      $.each(data.list, function(index, val) {
        wf += "<p>" // Opening paragraph tag
        wf += "<b>Day " + index + "</b>: " // Day
        wf += val.main.temp + "&degC" // Temperature
        wf += "<span> " + val.weather[0].description + "</span>"; // Description
        wf += "<img src='https://openweathermap.org/img/w/" + val.weather[0].icon + ".png'>" // Icon
        wf += "</p>" // Closing paragraph tag
      });
      $("#showWeatherForcast").html(wf);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showWeatherForcast"></div>

谢谢

3 个答案:

答案 0 :(得分:1)

您可以从时间戳中访问日期作为响应。定义您的日期名称(例如,用英语),将时间戳转换为new Date(乘以1000以获取正确的日期),然后使用本机方法获取日期。

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(data.list[0].dt * 1000);
var dayName = days[d.getDay()];
console.log(dayName)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        var key = "16c772c85cc7406ce72731159d78b31b";
        var city = "Pune,IN";
        var url = "https://api.openweathermap.org/data/2.5/forecast";
        $.ajax({
            url: url, //API Call
            dataType: "json",
            type: "GET",
            data: {
                q: city,
                appid: key,
                units: "metric",
                cnt: "17"
            },
            success: function(data) {
                const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
                const timesToDisplay = [0, 8, 16];
                let d;
                let dayName;
                var wf = "";
                wf += "<h2>" + data.city.name + "</h2>"; // City (displays once)
                $.each(data.list, function(index, val) {
                  if(timesToDisplay.includes(index)){
                    d = new Date(data.list[index].dt * 1000);
                    dayName = days[d.getDay()];
                    wf += "<p>" // Opening paragraph tag
                    wf += "<b>Day " + timesToDisplay.indexOf(index) + " (" + dayName + ")</b>: " // Day
                    wf += val.main.temp + "&degC" // Temperature
                    wf += "<span> " + val.weather[0].description + "</span>"; // Description
                    wf += "<img src='https://openweathermap.org/img/w/" + val.weather[0].icon + ".png'>" // Icon
                    wf += "</p>" // Closing paragraph tag
                  }
                });
                $("#showWeatherForcast").html(wf);
            }
        });
    });
</script>
<p id="showWeatherForcast"></p>

答案 1 :(得分:0)

API的响应包含DateTime作为时间戳。因此,您可以使用该时间戳来呈现UI。

wf += "<b>DateTime " + new Date(val.dt*1000).toISOString() + "</b>: "

在响应JSON中,您有一个列表,并且在每个对象内传递时间戳。要将时间转换为人类可读的格式,您可以乘以1000(毫秒),然后使用DateTime构造函数进行转换。

一旦您提取了日期,剩下的就是轻轻松松。 (-_-)

日提取过程

var allDays= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(data.list[0].dt * 1000); // to get the DateTime. 
var dayName = allDays[d.getDay()]; // It will give day index, and based on index we can get day name from the array. 
console.log(dayName)

希望这会有所帮助。

 $(document).ready(function() {
        var key = "16c772c85cc7406ce72731159d78b31b";
        var city = "Pune,IN";
        var url = "https://api.openweathermap.org/data/2.5/forecast";
        $.ajax({
            url: url, //API Call
            dataType: "json",
            type: "GET",
            data: {
                q: city,
                appid: key,
                units: "metric",
                cnt: "3"
            },
            success: function(data) {
                console.log('Received data:', data) // For testing
                
                var wf = "";
                wf += "<h2>" + data.city.name + "</h2>"; // City (displays once)
                $.each(data.list, function(index, val) {
                    wf += "<p>" // Opening paragraph tag
                    wf += "<b>Day " + index + "</b>: " // Day
                    wf += "<b>DateTime " + new Date(val.dt*1000).toISOString() + "</b>: " // DateTime
                    wf += val.main.temp + "&degC" // Temperature
                    wf += "<span> " + val.weather[0].description + "</span>"; // Description
                    wf += "<img src='https://openweathermap.org/img/w/" + val.weather[0].icon + ".png'>" // Icon
                    wf += "</p>" // Closing paragraph tag
                });
                $("#showWeatherForcast").html(wf);
            }
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showWeatherForcast"></div>

答案 2 :(得分:0)

您可以使用以下代码段从时间戳中查找日期。

const weekDay = new Date(val.dt * 1000).toLocaleString("en-us", {
    weekday: "long"
});

new Date构造函数期望以毫秒为单位的时间戳,但是API以秒为单位返回时间戳,这就是为什么需要* 1000的原因。

请参阅下面的完整实现。

$(document).ready(function() {
  var key = "16c772c85cc7406ce72731159d78b31b";
  var city = "Pune,IN";
  var url = "https://api.openweathermap.org/data/2.5/forecast";
  $.ajax({
    url: url, //API Call
    dataType: "json",
    type: "GET",
    data: {
      q: city,
      appid: key,
      units: "metric",
      cnt: "3"
    },
    success: function(data) {
      console.log('Received data:', data) // For testing
      var wf = "";
      wf += "<h2>" + data.city.name + "</h2>"; // City (displays once)
      $.each(data.list, function(index, val) {
        const weekDay = new Date(val.dt * 1000).toLocaleString("en-us", {
          weekday: "long"
        });
        wf += "<p>" // Opening paragraph tag
        wf += "<b>Day " + index + " (" + weekDay + ")" + "</b>: " // Day
        wf += val.main.temp + "&degC" // Temperature
        wf += "<span> " + val.weather[0].description + "</span>"; // Description
        wf += "<img src='https://openweathermap.org/img/w/" + val.weather[0].icon + ".png'>" // Icon
        wf += "</p>" // Closing paragraph tag
      });
      $("#showWeatherForcast").html(wf);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showWeatherForcast"></div>