Home > front end >  Using dayjs() to see if a date is after another one
Using dayjs() to see if a date is after another one

Time:05-01

I am trying to loop through an array and push the tasks that are after today in another array. Could someone tell me what I am doing wrong? (task.reminderDate is the correct type, I have used it in other functions and it works)

  taskList.forEach((task) => {
      if (dayjs().isAfter(dayjs(task.reminderDate))) {
        missedFilter.push(task);
      }
    });

CodePudding user response:

Your description doesn't describe what you are doing, but I am not sure which is wrong:

This is testing to see if "today" is after (task.reminderDate)

So, the output should be that the array "missedFilter" should be filled with tasks with a reminder date prior to today.

That seems like a reasonable thing to do, but you state that you want to push tasks that are after today into an array.

I don't think there's anything wrong with your actual code, but there may be something wrong with the semantics of what you intend to be doing.

e.g. if you genuinely want tasks with a reminderDate in the future, you should reverse the code:

var today = dayjs();
taskList.forEach((task) -> {
  if (dayjs(task.reminderDate).isAfter(today))) {
    missedFilter.push(task);
  }
});

(Note also, pushing the dayjs initializer outside the loop. Minor efficiency, but also helps with clarity.)

CodePudding user response:

I think you are misunderstanding how isAfter works.

console.log(dayjs("2031-01-01").isAfter(dayjs())); //This returns true

Currently you are comparing if today is after reminder date. So you want to change the order of your dates:

 if (dayjs(task.reminderDate).isAfter(dayjs()))

Now you are comparing if reminderDate is after today's date

  • Related