isotectz
isotectz

Reputation: 1

How to find number of days from given days in js?

I need to find number of days if i enter startDate and endDate.from the start_date to end_date i only want to retrieve weekdays i.e monday to friday along with the offcial_leave variable for_example:

let numberOfdays;
let startDate = '2022-04-04'; //yy-mm-dd format
let endDate  =  '2022-04-08';

// Below variable come from db and vary according the start and endate
// eg:- 2022-12-25 will be holiday if we select start and end in december
let holidays = ['2022-04-05', '2022-04-07' ]


numberOfdays => 3

// I want to return number of days to 3

How can i achieve this in in JavaScript

thanks

Upvotes: 0

Views: 92

Answers (1)

Aditya
Aditya

Reputation: 370

First convert the startDate and endDate to javascript Date. Then, declare a variable i to store while looping through the date. Also, declare holidayIndex which stores the current index at which holiday date needs to be checked with the current date.

Inside the loop, convert the date to YYYY-MM-DD format (original format) to check if the current date (isoDate) lies between a holiday, i.e., it is not a holiday date. If the holidayIndex is at last index of array, then just check if the current date (isoDate) is not in the holidays array. If not found, then increment numberOfDays variable.

Otherwise, a holiday date is found, hence no need to increment numberOfDays. Just increment holidayIndex to be ready to match the upcoming dates for next holiday date.

Here is the solution:

let numberOfdays = 0;
const startDate = '2022-04-04'; //yy-mm-dd format
const endDate = '2022-04-08';

// Below variable come from db and vary according the start and endate
// eg:- 2022-12-25 will be holiday if we select start and end in december
const holidays = ['2022-04-05', '2022-04-07'];
let holidayIndex = 0;

const start = new Date(startDate);
const end = new Date(endDate);
let i = start;

while (i <= end) {
  const isoDate = i.toISOString().split('T')[0];
  if (
    (holidayIndex < holidays.length - 1 && isoDate < holidays[holidayIndex] && isoDate > holidays[holidayIndex + 1]) ||
    formattedDate !== holidays[holidayIndex]
  ) {
    numberOfdays += 1;
  } else {
    holidayIndex += 1;
  }
  i.setDate(i.getDate() + 1);
}

Upvotes: 1

Related Questions