Calculate the number of selected days within a rolling two-week period between two given dates

I am in the process of developing a system for scheduled deliveries.

I have written a script that calculates the quantity of specific days of the week between two dates in dd/mm/yyyy format (UK).

var date0 = "01/02/2021";
var date1 = "31/01/2022";
var dayList = [1]; // Monday based on Sunday being 0
    
var result = countDays(dayList, parseDate(date0), parseDate(date1));
alert(result);
            
function parseDate(str) {
    var dmy = str.split('/');
    return new Date(+dmy[2], dmy[1] - 1, +dmy[0]);    
}           
            
function countDays(days, fromDate, toDate) {
    var ndays = 1 + Math.round((toDate-fromDate)/(24*3600*1000));
    var sum = function(a, b) {
        return a + Math.floor((ndays + (fromDate.getDay() + 6 - b) % 7) / 7);
    };
    return days.reduce(sum, 0);
}

In this case, when dayList=[1], it denotes 'Monday'. The script determines the total number of Mondays within the specified period and outputs the result to be 53 (since 01/02/2021 falls on a Monday).

This method is effective for tracking weekly occurrences of a particular day within a rolling week timeframe.

However, I am seeking guidance on modifying this approach to accommodate a rolling fortnight schedule.

For instance, I would like to calculate the frequency of both weekly Mondays and alternate Fridays within a rolling fortnight, rather than just a rolling week. This necessitates handling a combination of weekly and bi-weekly delivery schedules.

Consider this scenario: the client requests a shipment every Monday along with an additional delivery every other Friday.

Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri 
         x                           x               x 

Delivery schedules can vary significantly, with the rolling fortnight commencing on the user-provided start date.

The main challenge lies in determining the total number of days between the start and end dates while incorporating the concept of a 'rolling fortnight' into the calculation.

Answer №1

This solution is my own creation. Although it can be extended further, I have the capacity to store an array of delivery dates and calculate costs using additional information.

I trust that this will provide assistance.

function parseDate(str) {
  //handles the dd/mm/yyyy format UK date
    var dmy = str.split('/');
    return new Date(+dmy[2], dmy[1] - 1, + dmy[0]);     
}           

var fromDate = parseDate(document.getElementById("startdate").value);   // convert the date to js date  
var toDate = parseDate(document.getElementById("enddate").value);   // convert the date to js date  
var thisDay = fromDate.getDay();

var thisWeek;
var thisValue;
var testWeek;
var testElement;    
var result = 0;

while (fromDate <= toDate) {
    if (thisDay >= 14) {
        thisDay = 1;
    }
    thisWeek = Math.ceil(thisDay / 7);
    for (i = 1; i <= 14; i++) {
        testElement = document.getElementById("day" + i);
        testWeek = Math.ceil(i / 7);
        if ((testElement.checked) && (thisDay == i) && (thisWeek == testWeek)) {
            result++;
        }
    }
    thisDay++;
    fromDate.setDate(fromDate.getDate() + 1);
}           
alert("Number of deliveries is: " + result);
<input name="startdate" id="startdate" type="text" value="01/02/2021"/>
<input name="enddate" id="enddate" type="text" value="14/05/2021"/>
<table>
    <thead>
        <tr>
            <th>Mon</th>
            <th>Tue</th>
            <th>Wed</th>
            <th>Thu</th>
            <th>Fri</th>
            <th>Sat</th>
            <th>Sun</th>
            <th>Mon</th>
            <th>Tue</th>
            <th>Wed</th>
            <th>Thu</th>
            <th>Fri</th>
            <th>Sat</th>
            <th>Sun</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input class="tick checkboxgroup" type="checkbox" name="day1" id="day1" checked="checked"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day2" id="day2"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day3" id="day3"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day4" id="day4"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day5" id="day5"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day6" id="day6"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day7" id="day7"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day8" id="day8" checked="checked"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day9" id="day9"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day10" id="day10"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day11" id="day11"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day12" id="day12" checked="checked"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day13" id="day13"/></td>
            <td><input class="tick checkboxgroup" type="checkbox" name="day14" id="day14"/></td>
        </tr>
    </tbody>
</table>

Answer №2

If you want to determine the number of deliveries based on the day names between certain dates, one approach is to iterate through each day between the dates and tally up the occurrences of each day using a JavaScript reduce function:

const start = new Date('2022-11-17T03:24:00');
const endDate = new Date('2022-12-31T03:24:00');

const getDaysBetweenDates = function*(s, e) {
  let currentDate = s;
  
  while (currentDate < e) {
    yield currentDate.toLocaleDateString("en-us", { weekday: 'long' });
    currentDate = new Date(currentDate.getTime() + (24 * 60 * 60 * 1000));
  }
}

const dayCounts = Array.from(getDaysBetweenDates(start, endDate))
  .reduce((p, c) => ({
    ...p,
    [c]: (p.hasOwnProperty(c) ? p[c] + 1 : 1)
  }), {});

console.log(dayCounts.Monday + Math.floor(dayCounts.Friday / 2));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in JSON parsing: Unable to retrieve the length property of an undefined value

Currently, I am faced with a challenge on an HTML page wherein there are two input boxes designated for the user to enter origin and destination addresses. Upon submission by the user (via button click), I am utilizing JavaScript to capture these entries. ...

Attempting to achieve dynamic text changes in the Bootstrap dropdown button based on the selected item

I am currently using Bootstrap to style a dropdown button, and I want the button text to change based on the item selected from the dropdown. I believe that using JavaScript is the most effective way to achieve this, but I am not very familiar with it ye ...

retrieve scanned image information with node.js

Hey, I'm currently dealing with an issue that involves a form containing various types of questions such as boolean and text field answers. The user fills out the form, scans it, then uploads it to a node.js server. The node server will extract answe ...

Utilize the results of the "event's" output as a variable

Struggling with manipulating checkbox values? The `change` event on checkboxes might return an object like this: {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"} To transform the above object into a format that can be co ...

Can OpenLayers library be integrated into Vue CLI 3?

I am currently trying to integrate Openlayers with vue-cli-3, but it seems like I am missing something in the process. Initially, I installed Vue CLI using the following command: npm install @vue/cli -g Next, I added additional dependencies, specifically ...

Selenium is displaying outdated PageSource information and is failing to refresh after running Javascript

I am working on a console program in C# where Selenium is used to control a Chrome Browser Instance, and my goal is to extract all the links from a page. However, I have encountered an issue where the PageSource retrieved by Selenium differs from the actu ...

Halt! There is a Syntax Error: anticipating an expression, but instead received the keyword 'for'

I'm encountering an issue with this code. I need help to figure out how to print a loop inside dynamiHTML. Can anyone assist me? function createDiv(data){ var dynamicHTML = ''; alert(data.res2.length); dynamicHTML += '<div ...

Divergent timelines in mongoose and express.js

The issue arises when I specify my schema with type Date instead of String. Scenario I: var MySchema = new Schema({ created_at: {type: String, default: ''} }); In this schema declaration, I utilize moment.js moment-timezone module to set t ...

Incorporating a variable into a regular JavaScript pattern

In my JavaScript code, I have a variable assigned as var num = "x". How can I incorporate this variable into a regular pattern? var pattern = /"i want to include the variable num here"/i If I were working with a string, it would look something like this: ...

Does the term "JavaScript" serve as an erroneous substitute for "ECMAScript"?

From my perspective, it seems that: Modern browsers adhere to the ECMAScript Language Specification The trademark for "JavaScript" belongs to Oracle Corporation, currently used by Netscape and Mozilla According to page 43 of the 2018 ECMAScript spe ...

How can I resolve the error when Model.findOne() does not support a callback anymore?

I am facing an issue with this code as it is returning the error "Model.findOne() no longer accepts a callback". I need to resolve this issue without downgrading my mongoose version. `router.post('/login', async(req, res) => { const email = r ...

AngularJS UI.Router ActiveState implemented with a dropdown menu feature

I am currently working on creating a menu with dropdown functionality for multiple links within my application. My goal is to have the dropdown menu display as "active" when one of the links below is active. I have managed to make either the link in the ...

"Adjusting the Width of Inner Content in a Div

Here is the structure of a div: <div id="showHide"> <div>Alarm</div> <div>Alarmasdf</div> <div>Alarmasdffasdff</div> How can I obtain the width of the largest content, such as "Alarmasdffasdff"? I hav ...

Adjusting the color of a div based on the selection of a radio button contained within it

Looking for a way to change the color of a div when a radio button inside it is selected. I have been searching for a solution and haven't found anything that works yet. I want to display two divs side by side, each saying "choose this plan", with a c ...

Curious inquiries regarding the use of refresh tokens

I find myself in a state of confusion when it comes to the purpose and necessity of refresh tokens in conjunction with jsonwebtokens. It's clear that access tokens have a limited lifespan and refresh tokens are utilized to obtain new access tokens, bu ...

What is the method for utilizing HSL instead of RGB in the global declaration of SCSS using the JavaScript API

This is how my next.config.js file is structured: // next.config.js const env = require('./site.config').env; const Colour = require('sass').types.Color; const {r, g, b} = require('./site.config').customProperties; const wit ...

Execute with jQuery using Multiple Attribute Selector

I am attempting to input numeric values using a keyboard. My issue is as follows: the keyboard has an "Accept" button, and I have multiple text fields. I want to assign a different action for each text field. I attempted to use multiple attribute selector ...

organizing in order of the alphabet

I am looking to create a feature where users can sort a list alphabetically by clicking on the title, and then reverse the order with another click. I have attempted to implement this using different options, but so far, nothing seems to work as expected. ...

Injecting resolve values from UI router into Angular Jasmine tests

I am facing an issue in my Angular application where UI router resolves a promise into the controller. However, when attempting to test this controller using Karma, I receive an error about an unknown provider. How can I inject a mock object into the test ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...