Working with Date objects

Could someone please explain this to me. It is a weather app that shows 8 days forecast. I don’t understand starting from let today = , i understand newDate().getday() is going to give me a value between [0] and [6]. but then the +x part and the minus 7. How does this work?

                for (x = 0; x < dailyForecast.length; x++) {
                    let day = dailyForecast[x];
                    **let today = new Date().getDay() + x;**
**                    if (today > 6) {**
**                        today = today - 7;**
**                    }**

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

looks like +x adds 7 onto the current [daynumber]
So its new Date()getDay() !!which is today!!! then +x. Which adds 7 onto that value.
then to get today you have to minus the 7 again to get to the value. Now why am i getting an 8 days forecast and not 7?

today here is a misleading variable name. The new Date().getDay() is the objective today value, while x is how many days from today we’re looking.

Today is July 13 2021, the getDate() of today would return a 2. So today’s x would be 0, and today’s day index 2. Tomorrow’s x would be 1, and the day index would be today’s plus x, 2+1 or 3. And so on.

Now, on the 18th, x would be 5 (five days from today). Now today’s weekday index is still 2, so the index for the 18th is 2+5, or 7. But our weekdays can only be 0 to 6 inclusive, so we reduce the 7 by 7, causing the index to “wrap” back to 0.

On the 19th, x is 6 as we’re looking six days out. So that index would be 2+6… Which is still outside the range. So we reduce it by 7, bringing it’s day index to 1, for Monday.

If i were naming that variable, I’d change today to dayBeingForecast or something - make it explicit what the variable actually represents.

1 Like

Sounds like an “off-by-one error”, but what does your weather data look like?

Thank you mate. That is exactly what i was looking for. The 2 +[0] was throwing me off. It seems the object itself has 8 weather days [0]-[7] and that why it must be making 8 days of forecast… Is there a way to only pull the first 7 days of the forecast. x = 0 ; x < dailyforecastLength//8//; x++

oooh I got it

if(x === 7){

Thanks again Boss. Great explanation.

Or, if you knowyou only want 7 days of the 8, set the end condition of the loop explicitly - rather than using x < dailyForecast.length just use x < 7 in the for loop.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.