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

Viewed 689

The reason why want to convert to local time is so that I can change the background with images. So in the end I want to have time output like 12:00 or 20:00. My JSON looks like:

{
  "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":{
  }
},

2 Answers

That works fine. Just run the snippet.

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");

If I've catch your question correctly, you need something like this (just for example, you can refactor it more beautiful):

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

We multiplied seconds to 1000, because timestamps in JS lives in milliseconds instead of seconds like a Unix OS.

After that you can use Date objects to get what you want via Date API. I suppose, you want .getHours() method.

Related