DEV Community 👩‍💻👨‍💻

Margaret W.N
Margaret W.N

Posted on

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

Top comments (0)

CSS margins

Stop by this week's meme thread!