javascriptdate

How to convert the sunset UNIX timestamp from OpenWeather API to local time?


I'm using the OpenWeather API to get the sunset time for a specific city. The API returns the sunset time as a UNIX timestamp, and I want to convert this timestamp into the local time of the specific city using JavaScript.

  "name": "Mountain View"
  "sys": {
    "type": 1,
    "id": 5122,
    "country": "US",
    "sunrise": 1681565616,
    "sunset": 1681612963
  },
  "timezone": -25200,

I've tried creating a new Date object using the sunset timestamp like this:

var sunsetTimestamp = 1681612963;
var sunsetDate = new Date(sunsetTimestamp * 1000);
console.log(sunsetDate)

However, this doesn't give me the correct local time of sunset.


Solution

  • You can add sunsetTimestamp to timezone before creating the date. The date it creates doesn't equal the UTC date of Mountain View at sunset, but it does output the timezone-adjusted value for the sunset.

    var sunsetTimestamp = 1681612963;
    var timezone = -25200;
    var sunsetDate = new Date((sunsetTimestamp + timezone) * 1000);
    console.log(sunsetDate)