如何将天气api转换为本地时间(ReactJS / JavaScript)

要转换为本地时间的原因是为了可以更改图像的背景。因此,最后我想输出12:00或20:00之类的时间。我的JSON看起来像:

{
  "lat":52.37,"lon":4.89,"timezone":"Europe/Amsterdam","timezone_offset":7200,"current":{
    "dt":1593619296,"sunrise":1593573770,"sunset":1593633935,"temp":20.09,"feels_like":13.21,"pressure":1006,"humidity":56,"dew_point":11.05,"uvi":6.73,"clouds":20,"visibility":10000,"wind_speed":10.3,"wind_deg":260,"weather":[
    {
      "id":801,"main":"Clouds","description":"few clouds","icon":"02d"
    }
  ],"rain":{
  }
},

iCMS 回答:如何将天气api转换为本地时间(ReactJS / JavaScript)

那很好。只需运行摘要即可。

const api_res = {
    "lat": 52.37,"lon": 4.89,"timezone": "Europe/Amsterdam","timezone_offset": 7200,"current": {
        "dt": 1593619296,"sunrise": 1593573770,"sunset": 1593633935,"temp": 20.09,"feels_like": 13.21,"pressure": 1006,"humidity": 56,"dew_point": 11.05,"uvi": 6.73,"clouds": 20,"visibility": 10000,"wind_speed": 10.3,"wind_deg": 260,"weather": [{
            "id": 801,"main": "Clouds","description": "few clouds","icon": "02d"
        }],"rain": {}
    }
}

function format_date(x) {
  x = String(x);
  if(x.length === 1) {
    return "0"+x;
  } else {
    return x;
  }
}

seconds_to_sunrise = api_res["current"]["sunrise"];
var d = new Date(0);
d.setUTCSeconds(seconds_to_sunrise);
console.log(format_date(d.getHours())+":00");

,

如果我正确地找到了您的问题,则需要这样的东西(例如,您可以将其重构得更漂亮):

const dt = new Date(weatherData.current.dt * 1000);
const sunrise = new Date(weatherData.current.sunrise * 1000);
const sunset = new Date(weatherData.current.sunset * 1000);

我们将秒数乘以1000,因为JS中的时间戳以毫秒为单位,而不是Unix OS的秒。

之后,您可以使用Date对象通过Date API获得所需的内容。我想,您想要.getHours()方法。

本文链接:https://www.f2er.com/2019419.html

大家都在问