Как получить количество дней между двумя датами, исключая выходные дни, с помощью Moment.js?

Пользователь

от christine , в категории: JavaScript , 10 месяцев назад

Как получить количество дней между двумя датами, исключая выходные дни, с помощью Moment.js?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

2 ответа

Пользователь

от francisco.friesen , 10 месяцев назад

@christine 

Существует несколько способов получить количество дней между двумя датами, исключая выходные дни, с помощью Moment.js.


Это может быть сделано с использованием следующей формулы:

  1. Создайте объект Moment для начальной даты и конечной даты.
1
2
const startDate = moment('2021-01-01');
const endDate = moment('2021-01-10');


  1. Создайте пустой массив для хранения дней между этими датами.
1
const daysBetween = [];


  1. Используйте цикл для прохода через каждый день между начальной и конечной датами и проверки, является ли этот день рабочим днем.
1
2
3
4
5
6
while(startDate <= endDate){
  if(startDate.day() !== 0 && startDate.day() !== 6){
    daysBetween.push(startDate.clone());
  }
  startDate.add(1, 'days');
}


  1. Получите количество дней между этими датами, исключая выходные дни, с помощью длины массива daysBetween.
1
const numberOfDays = daysBetween.length;


Теперь numberOfDays будет содержать количество дней между начальной и конечной датами, исключая выходные дни.


Вот полный пример:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const moment = require('moment');

const startDate = moment('2021-01-01');
const endDate = moment('2021-01-10');

const daysBetween = [];

while(startDate <= endDate){
  if(startDate.day() !== 0 && startDate.day() !== 6){
    daysBetween.push(startDate.clone());
  }
  startDate.add(1, 'days');
}

const numberOfDays = daysBetween.length;

console.log(numberOfDays); // Output: 6


Обратите внимание, что вы должны установить Moment.js перед использованием и убедиться, что у вас установлена библиотека Moment.js.

Пользователь

от francisco.friesen , 10 месяцев назад

@christine 

You can use the diff method in Moment.js to get the number of days between two dates. To exclude weekends, you can loop through each day between the two dates and check if it is a weekend day (Saturday or Sunday).


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const moment = require('moment');

function getBusinessDays(startDate, endDate) {
  let currentDate = moment(startDate);
  const endDateMoment = moment(endDate);

  let businessDays = 0;
  while (currentDate.isSameOrBefore(endDateMoment)) {
    if (currentDate.day() !== 0 && currentDate.day() !== 6) {
      businessDays++;
    }
    currentDate.add(1, 'day');
  }

  return businessDays;
}

// Example usage:
const startDate = '2021-11-01'; // Format: 'YYYY-MM-DD'
const endDate = '2021-11-10';

const days = getBusinessDays(startDate, endDate);
console.log(days); // Output: 6


This example defines a getBusinessDays function that takes the startDate and endDate as arguments. The function uses a currentDate variable that starts from the startDate and loops through each day until the endDate. If the currentDate is not a Sunday (0) or Saturday (6), it increments the businessDays counter.


Finally, the function returns the total number of business days between the two dates. In this example, the output will be 6, excluding the weekends.