Home > Net >  Calculate days from a date range that fall in X month & Y month
Calculate days from a date range that fall in X month & Y month

Time:09-09

Within a calendar year I have two season one runs May to September & the other runs October to April.

I have a form where a user selects a check-in and check-out date. I basically need to figure out how many days from their selected stay falls in each of the seasons.

I'm unsure how I go about this? I'm currently using date-fns and formatDistanceStrict to workout how many days they are staying just not sure how to do the above any guidance would be appreciated

CodePudding user response:

Here is a way to do it in a compreensive way

let startDate = "2022-01-01";
let endDate = "2022-10-30";
let mayToSeptember;
let octoberToApril;
// Add all days between start and end date to array
let dateArray = [];
while (startDate <= endDate) {
    dateArray.push(new Date(startDate));
    
}

// each day in dateArray loop
for (let i = 0; i < dateArray.length; i  ) {
    let day = dateArray[i];    
    let month = day.getMonth();
    // check if month is May to September
    if (month >= 4 && month <= 8) {
        mayToSeptember  ;
    }
    // check if month is October to April
    else {
        octoberToApril  ;
    }
}

CodePudding user response:

Try using the Intl.RelativeTimeFormat

const dateFormatter = new Intl.RelativeTimeFormat('en');

const diff = new Date() - new Date('05/01/2023');
console.log(dateFormatter.format(-diff / (1000 * 60 * 60 * 24), 'days')); // logs how many days this is in

  • Related