Home > Blockchain >  How do I retrieve the most recent {day of the week} with Moment js?
How do I retrieve the most recent {day of the week} with Moment js?

Time:11-16

I need to create function that produces a date range based on when a user's meeting day is. The users meet on different days, in this example I will use "John" who meets with his group on Wednesdays. The two dates I need are the most recent Wednesday and the next Wednesday. For example if today is Monday Nov 15th the function should return 11/10/2021 & 11/17/2021

My current code only works on the meeting day or after it has already happened because it pulls this week's Wednesday and next week's Wednesday...

  const DateRange = () => {
    switch (user.groups[0].meetingDay) {
      case "monday":
        return [1, 8];
      case "tuesday":
        return [2, 9];
      case "wednesday":
        return [3, 10];
      case "thursday":
        return [4, 11];
      case "friday":
        return [5, 12];
      case "saturday":
        return [6, 13];
      case "sunday":
        return [0, 7];
    }
  };

  const firstNumber = DateRange().push(0);
  const secondNumber = DateRange().pop(0);
  const goalsDateRangeStart = moment().day(firstNumber).format("l");
  const goalsDateRangeEnd = moment().day(secondNumber).format("l");
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

When the code above is used on Nov 15th it will give me 11/17/2021-11/24/2021

CodePudding user response:

Moment is no longer supported. Here is a JavaScript Date API solution.

NOTE: day values range from 0 (Sunday) - 6 (Saturday)

The starting date is calculated by: date value (15th) - (today's day value - (#days in a week - the day parameter value)

15 - ( 1 7 - 3) = 10 - starting date is the 10th

Ending date is 7 days later:

10 7 = 17th - ending day is the 17th

The code ensures separate date objects are used for each date.

It calls the function with today's date with meetings set for Wednesday (3). The function returns an object in the form {start: Date, end: Date}:

// Takes a Date object (default today) and int Day of the week (default Monday)
function dateRange(date = new Date(), day = 0) {
  const start = new Date(date.setDate(date.getDate() - (date.getDay()   (7 - day))));
  return {
    start: start,
    end: new Date(new Date(start).setDate(start.getDate()   7))
  };
}
// Call function with today's date with meetings scheduled for Wednesdays
const range = dateRange(new Date(), 3);
console.log(range.start.toDateString(),'-', range.end.toDateString());
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related