Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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?

Thanks!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

You push a day (result.push(current.clone())) exactly once, so you can't expect to have more than one date per day. You can make a second if statement with this condition: (current.day(7 + dia).isSameOrBefore(end)) and push it second time.

Also, in js, when first condition in if is met, the other are not resolved.

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());
    }

    if (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>

about 4 years ago · Juan Pablo Isaza Report

0

Here is an alternative if want to do this in three easy lines using the Date API.

I offer this alternative considering momentjs is 17,000+ lines of code in 42k.

For your consideration.

While processing the range from start to finish (inclusive)

  1. convert the date to a dateString and look for Fri or Sun or Wed
  2. if found -> Add the date to the result array
  3. check the next date

const startDate = new Date('2021', '11', '1');
const endDate = new Date('2021', '11', '31');
var tempDate = new Date('2021', '11', '1');
var result = [];

while (tempDate.valueOf() !== endDate.valueOf()) {
  if (/Fri|Sun|Wed/.test(tempDate.toDateString())) result.push(new Date(tempDate));
  tempDate.setDate(tempDate.getDate() + 1);
}
result.forEach(day => console.log(day.toDateString(), day.toISOString().replace("T",' ')));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!