I am making a simple react app with OpenWeatherMap API. I need date info from that API to show which day is the current day. The API returns me a dt
object I think this is related to date but I can’t use it. How can I convert it to a valid date string? I found a topic about this issue but the answer did not satisfy me.
{ "lat": 38.783, "lon": 41.0466, "timezone": "Europe/Istanbul", "timezone_offset": 10800, "current": { "dt": 1610733742, "sunrise": 1610685149, "sunset": 1610720251, "temp": 274.58, "feels_like": 270.28,
Advertisement
Answer
I found the answer.
We can convert to dt object to JS date object. Like this.
The tricky part is we have to convert day object to string.
const dt = 1610685149 var day = new Date(dt*1000); console.log(day.toUTCString()) // 'Fri, 15 Jan 2021 04:32:29 GMT' console.log(day.toDateString()) // 'Fri Jan 15 2021' console.log(day.toISOString()) // '2021-01-15T04:32:29.000Z' console.log(day.toString()) // 'Fri Jan 15 2021 07:32:29 GMT+0300 (GMT+03:00)'
I found the answer from here w3schools.com display dates
End of the day, I implement this solution to my code just like this.
function createDate(dt, type) { var day = new Date(dt * 1000); if (type == "long") { let options = { weekday: "long", year: "numeric", month: "long", day: "numeric", }; return day.toLocaleString("en-us", options); // Friday, January 15, 2021 } else { return day.toLocaleString("en-us", { weekday: "long" }); // Friday } }
EDIT: I found the more elegant way to convert to string from here. And also check this MDN resource about toLocaleString()