Momentjs Next Business Day
Asked Answered
D

3

5

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");
        }
Discommodity answered 17/7, 2015 at 13:20 Comment(1)
and you need a array of all holiday, for if else check tooKokanee
D
9

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");
    }
Douro answered 17/7, 2015 at 14:56 Comment(1)
Does this respect holidays?Collimator
C
4

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);
}
Counterspy answered 4/1, 2019 at 7:47 Comment(0)
O
0
if (moment().day() === 5 || moment().day() === 6) { // friday or saturday -> show monday
    $scope.businessDay=moment().day(8).format("MMMM Do YYYY");
} else { // other days, show next day
    $scope.businessDay= moment().add('days', 1).format("MMMM Do YYYY");
}
Orizaba answered 8/12, 2023 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.