How to get the next day skipping the weekend using moment.js?

by darrion.kuhn , in category: Javascript , a year ago

How to get the next day skipping the weekend using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , a year ago

@darrion.kuhn 

To get the next day while skipping the weekend using Moment.js, you can use the add() method along with the day() method to check if the next day is a weekend day and increment accordingly. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const today = moment();
let nextDay = today.clone().add(1, 'days');

// Check if the next day is a weekend day (6 = Saturday, 0 = Sunday)
while(nextDay.day() === 6 || nextDay.day() === 0) {
  nextDay = nextDay.add(1, 'days');
}

// Display the next day skipping the weekend
console.log(nextDay.format('YYYY-MM-DD'));


This code will get the current date using moment(), then clone it to a new variable nextDay, adding one day to it. It will then check if the day is a Saturday or Sunday using the day() method. If it is, it will increment nextDay by another day until it's a weekday.


Finally, it will display the next day skipping the weekend using the format() method with the desired format (e.g., 'YYYY-MM-DD').