I have an array that contains multiple Dates and, from this array, I want to return an array that contains only the Dates that belong to the current week. How can I do this?
I have an array that contains multiple Dates and, from this array, I want to return an array that contains only the Dates that belong to the current week. How can I do this?
Share Improve this question edited Jul 6, 2017 at 21:08 flpn asked Jul 6, 2017 at 20:56 flpnflpn 1,9784 gold badges20 silver badges31 bronze badges 7- Define "list" ... html, array ,other? Please take some time to read through How to Ask and minimal reproducible example – charlietfl Commented Jul 6, 2017 at 20:59
- What is the format of the dates? – sissonb Commented Jul 6, 2017 at 20:59
- @charlietfl, an array – flpn Commented Jul 6, 2017 at 21:00
- Do some research and spend time a little. Start by getWeek – Volem Commented Jul 6, 2017 at 21:01
- @sissonb I'm working with the Date class – flpn Commented Jul 6, 2017 at 21:03
3 Answers
Reset to default 5The only hard part about this is finding the time frame of the week. To do that you could do:
function getWeekDates() {
let now = new Date();
let dayOfWeek = now.getDay(); //0-6
let numDay = now.getDate();
let start = new Date(now); //copy
start.setDate(numDay - dayOfWeek);
start.setHours(0, 0, 0, 0);
let end = new Date(now); //copy
end.setDate(numDay + (7 - dayOfWeek));
end.setHours(0, 0, 0, 0);
return [start, end];
}
let [start, end] = getWeekDates();
console.log(start.toLocaleString(), end.toLocaleString());
Now, to filter them:
function filterDatesByCurrentWeek(dates){
let [start, end] = getWeekDates();
return dates.filter(d => +d >= +start && +d < +end);
}
This is assuming your dates are date objects. If they are not, you'll need a way to parse them and get the date object.
I would remend using a library like momentjs.
You could easily filter the array by doing
var currentDate = moment();
var allDates = [...];
var filtered = allDates.filter(date => moment(date).isSame(currentDate, 'week');
Here's an example using filter.
let outOfWeek = new Date();
outOfWeek.setDate(outOfWeek.getDate() + 7)
const dateList = [
new Date(),
outOfWeek
]
const monthDay = new Date().getDate();
const weekDay = new Date().getDay();
const daysToSunday = 7 - weekDay;
const daysFromSunday = weekDay;
const setDateToMidnight = (date) =>{
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
let maxDate = new Date();
maxDate.setDate(monthDay + daysToSunday);
setDateToMidnight(maxDate);
let minDate = new Date();
minDate.setDate(monthDay - daysFromSunday);
setDateToMidnight(minDate);
filteredDates = dateList.filter((date) => {
if (date.getTime() < maxDate.getTime() && date.getTime() >= minDate.getTime()) {
return true;
} else {
return false;
}
})
console.log(dateList);
console.log(filteredDates);
https://jsfiddle/qorb6ruL/5/