Autoupdate days of the week from open weather data.
Margaret W.N
Posted on September 28, 2020
I finally fixed the last bug in my weather app! The goal was to update the day of the week from the current date.
const nextDay = [document.querySelectorAll('#nextDay')]
const daysOfTheWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let dayOftheWeek = nextDay[0]
for (i = 0; i < 7; i++) {
let timeInUnix = data[i].dt
let dateFromUnix = new Date(timeInUnix * 1000)
dayOftheWeek[i].innerText = daysOfTheWeek[dateFromUnix.getDay()]
if(i === 0 ){
dayOftheWeek[i].innerText = 'Tommorrow';
}
}
The code explained:
All the card elements have the same Id of #nextDay
. I'm using document.querySelectorAll()
to fetch all of them and store them in an array. I'll be looping through this array as i update the correct day of the week from today. I'm fetching the data from open weather API, the dt property is part of the data received from open weather. Since I'm fetching weekly data there are 7 dt properties hence I also have to loop through the properties updating them accordingly.
The dt property is in Unix, I'm multiplying by 1000 to convert to milliseconds then passing the value to the date object. The date object returns the date. From the date, I then attach a getDay()
function which returns the day of the week as an integer between 0 and 6 where 0 is Sunday. I declared a variable with an array of the days of the week. To get the name of the day of the week ill pass in the integer generated by getDay()
function as an index of my daysOfTheWeek[]
array.
Link to app: Weather app
Key lessons from today, read the documentation! I didn't know the dt property existed until I asked for help.
That's it for day 74
Let's do this again tomorrow
Posted on September 28, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.