繁体   English   中英

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

[英]How do I convert weather api to local time (ReactJS/JavaScript)

想要转换为当地时间的原因是我可以用图像更改背景。 所以最后我想有时间 output 像 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":{ } },

这很好用。 只需运行代码段。

 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 操作系统那样以秒为单位。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM