Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capture every Friday, Sunday and Wednesday between two dates

Goodnight. I’m trying to capture every Friday, Sunday and Wednesday between two dates using Moment.js. I couldn’t understand why it doesn’t capture the days:

  • 2021-12-08
  • 2021-12-10

I managed to get this far:

const allDays = [0, 3, 5];

function formatToPush(dt_inicio, dt_final, dia, horas) {

    let start = moment(dt_inicio);
    let end = moment(dt_final);

    let result = [];
    let datas = [];
    let current = start.clone();

    if ((current.day(dia).isSameOrAfter(start)) || (current.day(dia).isSameOrAfter(end)) || (current.day(7 + dia).isSameOrBefore(end))) {
        result.push(current.clone());
    }

    result.map(m => {
        horas.map(h => {
            m.set({ hour: h.split(':')[0], minute: h.split(':')[1], second: 0, millisecond: 0 });
            datas.push(m.format('YYYY-MM-DD HH:mm:ss'))
        })
    });

    return datas;
}

let final = [];

for (let i in allDays) {
    final.push(...formatToPush('2021-12-01', '2021-12-10', allDays[i], ["10:00", "16:00", "22:30"]))
}

console.log(final)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Can anyone help me find the error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

The condition for whether the day is within the bounds is always true for either or both of the first two clauses. This means the whole expression is true without evaluating the third clause which is the one that could set the date to one of the later dates you are missing. Since you aren’t running that if-statement in a loop, it will only ever push one date to the result array.

A more generalized algorithm would use a loop.

let current = start.clone();
if (current.day(dia).isSameOrAfter(start) && current.isSameOrBefore(end)) {
  result.push(current.clone());
}
while (current.day(7 + dia).isSameOrAfter(start) && current.isSameOrBefore(end)) {
  result.push(current.clone());
}

Note: I also changed the conjunction to && because with the loop, isAfter would always be true. Also I omitted current.day(dia) in the second clause since the first one is already setting the day of the week for current.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading