Momentjs Next Business Day

2019-09-10 04:26发布

问题:

I'm trying to get the next business day with my code, but it's not working correctly. It's just showing the next day. I've tried to check other questions to find the error, but I still can't figure it out.

This question applies to my own but not exactly:

How to exclude weekends between two dates using Moment.js

 $scope.businessDay = new Date();

        if (moment().day() === 5) { // friday, show monday
            // set to monday
            $scope.businessDay=moment().weekday(8).format("MMMM Do YYYY");
        }
        if (moment().day() === 6) { // saturday, show monday
            // set to monday
            $scope.businessDay=moment().weekday(8).format("MMMM Do YYYY");
        }
        else { // other days, show next day
            $scope.businessDay= moment().add('days', 1).format("MMMM Do YYYY");
        }

回答1:

It's working fine. You've just missed an else

    if (moment().day() === 5) { // friday, show monday
        // set to monday
        $scope.businessDay=moment().weekday(8).format("MMMM Do YYYY");
--> } else if (moment().day() === 6) { // saturday, show monday
        // set to monday
        $scope.businessDay=moment().weekday(8).format("MMMM Do YYYY");
    }
    else { // other days, show next day
        $scope.businessDay= moment().add('days', 1).format("MMMM Do YYYY");
    }


回答2:

Here's another version. This doesn't depend on starting day of week:

function buildNextValidDate(dateFormat = 'MMMM Do YYYY') {
  let dayIncrement = 1;

  if (moment().day() === 5) {
    // set to monday
    dayIncrement = 3;
  } else if (moment().day() === 6) {
    // set to monday
    dayIncrement = 2;
  }

  return moment().add(dayIncrement, 'd').format(dateFormat);
}