@ZeroKilledMay 10.2009 — #the only way i can think of is to iterate the two date object and have a counting variable for sundays and saturdays. <i> </i>function countSatSun(start, end){ if(end < start)return; //avoid infinite loop; for(var count = {sun:0, sat:0}; start < end; start.setDate(start.getDate() + 1)){ if(start.getDay() == 0)count.sun++; else if(start.getDay() == 6)count.sat++; } return count; }
@felgallMay 10.2009 — #Subtract the one date from the other and divide by 7. That gives you whole weeks for which there is one each Saturday and Sunday. If the start date is a Sunday or end Date is a Saturday but not both then add one to the previous result. No loop is required.
@ZeroKilledMay 11.2009 — #1. How does the count get set to zero with {sun:0, sat:0} ?
3. Is count a global variable defined as count = {sat:0, sun:0} someplace or is it local to the function?[/quote]
[b]count[/b] is a local variable defined in [b]for[/b] loop, specifically in the initialization part. remember that loops statement doesn't create a scope, so before iterating the variable is created and become a local variable in the function' scope.
2. Where or when does count get assigned as count.sun and count.sat?[/quote] it is a literal object created on the fly, again, initialized in the [b]for[/b] statement.
4. If a local variable, what is returned with return count and how would it be read in the returned to code? [/quote] i guess you can now answer yourself this question. it return an object with two property. i used an object because function can't return two separate values on a single call. i could have used an array as well.
maybe the following code will make more sense to you. in fact, this was my initial code: <i> </i>function countSatSun(start, end){ if(end < start)return; //avoid infinite loop; var count = {sun:0, sat:0}; for([color=blue]/*empty, notice semicolon isn't inside this comment*/[/color]; start < end; start.setDate(start.getDate() + 1)){ if(start.getDay() == 0)count.sun++; else if(start.getDay() == 6)count.sat++; } return count; }
as you can see the variable could be initialized in the function's body. i'm not sure if what had confused you is the fact that we have the habit of initializing the iterator in the [b]for[/b] loop. however, in my code that wasn't the case. it was just a matter of mood that i declared the variable in [b]for[/b] initialization.