Autoupdate days of the week from open weather data.

mtee

Margaret W.N

Posted on September 28, 2020

Autoupdate days of the week from open weather data.

I finally fixed the last bug in my weather app! The goal was to update the day of the week from the current date.

The static site:
Alt Text
The code:

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';
        }
}

Enter fullscreen mode Exit fullscreen mode

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.

The output from the code:
Alt Text

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

πŸ’– πŸ’ͺ πŸ™… 🚩
mtee
Margaret W.N

Posted on September 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 23 of 100DaysOfCode
javascript Day 23 of 100DaysOfCode

October 3, 2024

Day21 of 100DaysOfCode
javascript Day21 of 100DaysOfCode

August 22, 2024

Day22 of 100DaysOfCode
javascript Day22 of 100DaysOfCode

September 7, 2024

Day 2 of #100daysofMiva Coding Challenge
100daysofmiva Day 2 of #100daysofMiva Coding Challenge

August 22, 2024