Reputation: 145
I got a weeknumber from a jquery datepicker, when a user selects a date. But now I want to get all the days within that week.
I could add a click event that loops through all the td's of the tr the selected date is in and graps it's value but I'm looking for a more reliable way.
So my question is, given a certain date and a weeknumber (iso 8601 formatted), how can you derive the other dates within that week with javascript?
Upvotes: 3
Views: 1322
Reputation: 596
You can solve it by subtracting the selected date day (getDate()), with the day of the week (getDay()). This way you have the first day of the week. Then you can use a for loop till 7, to get all the other days. You don't need the weeknumber.
var selected_date = $(this).datepicker('getDate'); //the date the user has clicked
var first_day_of_the_week = new Date(selected_date.getFullYear(),selected_date.getMonth(),selected_date.getDate() - selected_date.getDay() + 1);
var days = [];
for(var i = 0; i < 7; i++){
var day = new Date(first_day_of_the_week.getFullYear(),
first_day_of_the_week.getMonth(),
first_day_of_the_week.getDate() + i);
days.push(day);
}
console.log(days);
Upvotes: 7
Reputation: 98796
There’s a JavaScript implementation of a getWeek
function here:
You could run that on dates seven days either side of your date, and keep the dates for which the week number is the same.
Upvotes: 0