簡體   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