Get the days of the week from a date - Javascript

0

Create a function that brings me the days of the week from Monday to Sunday :

    weekLabel(current) {
        const week = [];
        const weekFormat = [];
        current.setDate(((current.getDate() - current.getDay()) + 1));
        for (let i = 0; i < 7; i++) {
          week.push(new Date(current));
          current.setDate(current.getDate() + 1);
        }
        week.forEach((w) => {
          weekFormat.push(moment(w).format('DD/MM/YYYY'));
        });
        return weekFormat;
      },

In which current is what is waiting for the function that happens in this case a date ... this works correctly but when I pass a date on a Sunday and it returns me the days of the other week. I know that the week starts from Sunday but I would like to know if I can start from Monday

    
asked by Piero Pajares 15.07.2018 в 19:56
source

1 answer

1

The problem is that getDay () will always return you 0 on Sunday, a solution may be to include an If so that when I arrive on Sunday I took it as if it were the Seventh day of the week. You can do it in the following way:

function weekLabel(current) {
const week = [];
const weekFormat = [];

if(current.getDay() == 0){//En los casos en que es domingo, restar como si fuera septimo dia y no cero
    current.setDate(((current.getDate() - 7) + 1));
}else{
    current.setDate(((current.getDate() - current.getDay()) + 1));
}

for (let i = 0; i < 7; i++) {
    week.push(new Date(current));
    current.setDate(current.getDate()+1);
}
week.forEach((w) => {
    weekFormat.push(moment(w).format('DD/MM/YYYY'));
});
return weekFormat;

}

I already tried it and it gave results. I hope you serve

    
answered by 15.07.2018 / 22:06
source