0

I am currently creating an app through React which connects to the OpenWeatherAPI. The app is when someone types in there location it pulls the weather of their specific location. The issue I am having is converting the timestamp of the specific location to a local time. I have used MomentJs, but the time keeps up coming wrong. The issue for example if someone chooses Tokyo, Japan I want it to show that the sunrise will be 6:50 am their local time. Right now I am getting back Mon Dec 28 2020 16:50:24 GMT-0500 (Eastern Standard Time).

This is the API snippet:

{
  "dt": 1609176171,
    "sys": {
        "type": 1,
        "id": 8074,
        "country": "JP",
        "sunrise": 1609192224,
        "sunset": 1609227369
    },
    "timezone": 32400,
    "id": 1862143,
    "name": "Horinouchi",
    "cod": 200
}

terrymorse
  • 6,771
  • 1
  • 21
  • 27
MeowHowe
  • 54
  • 5
  • Does this answer your question? - https://stackoverflow.com/a/18330682/13747848 – kmp Dec 28 '20 at 18:32

1 Answers1

1

You can create a date for the sunrise by adding the timezone value.

The example below will produce a date and time in the timezone of the weather record (Horinouchi), NOT the timezone of the user.

const data = {
  "dt": 1609176171,
  "sys": {
    "type": 1,
    "id": 8074,
    "country": "JP",
    "sunrise": 1609192224,
    "sunset": 1609227369
  },
  "timezone": 32400,
  "id": 1862143,
  "name": "Horinouchi",
  "cod": 200
};

// extract sunrise and timezone offset in UNIX epoch seconds
const {
  sys: {sunrise},
  timezone
} = data;

// create Date object for sunrise with timezone offset
const srTime = new Date((sunrise+timezone)*1000);

// convert number to a 2-digit string
const twoDigits = (val) => {
  return ('0' + val).slice(-2);
};

const year = srTime.getUTCFullYear();
const month = twoDigits(srTime.getUTCMonth()+1);
const dayOfMonth = twoDigits(srTime.getUTCDate());
const hours = twoDigits(srTime.getUTCHours());
const minutes = twoDigits(srTime.getUTCMinutes());
const seconds = twoDigits(srTime.getUTCSeconds());

console.log(`${year}-${month}-${dayOfMonth} ${hours}:${minutes}:${seconds}`);

Note that the date will be in UTC time, so be sure to display it for the user that way (i.e. don't display it with a local offset).

To display the UTC date, use Date.prototype:

terrymorse
  • 6,771
  • 1
  • 21
  • 27
  • Thank You! But I keep on getting 12-29-2020 01:50:24 instead of 6:50 do you know what would be the reason? – MeowHowe Dec 28 '20 at 18:51
  • @MeowHowe That's probably because you're still displaying the result with your computer's local timezone offset (GMT -5). See my updated answer above for how to display in UTC timezone. – terrymorse Dec 28 '20 at 19:04