Summing the total days between two dates within an array

My goal is to determine the number of days between two dates stored in an array.

For example:

StartDate = new Array("08 Feb 1954", "16 Sep 1955", "25 Nov 1955",
                      "19 Oct 1956", "13 Jun 1958", "08 Aug 1958", 
                      "05 Sep 1958", "02 Jan 1959", "19 Jun 1959", 
                      "07 Aug 1959", "03 Nov 1959", "11 Dec 1959", 
                      "15 Apr 1960", "20 May 1960", "21 Oct 1960", 
                      "11 Nov 1960", "20 Dec 1960");

EndDate   = new Array("26 Aug 1955", "28 Oct 1955", "07 Sep 1956",
                      "23 Nov 1956", "25 Jul 1958", "22 Aug 1958",
                      "07 Nov 1958", "17 Apr 1959", "31 Jul 1959",
                      "02 Oct 1959", "04 Dec 1959", "25 Dec 1959",
                      "13 May 1960", "10 Jun 1960", "04 Nov 1960",
                      "18 Nov 1960", "14 Feb 1961");

for ( var i = 0; (i < 17); i++ )
{
     numdays = date_diff_indays(StartDate[i], EndDate[i]);
     TotalDays += numdays;
}

I am exploring how to transform the StartDate and EndDate arrays into a multidimensional array for calculations.

Here is my current calculation approach:

var date_diff_indays = function (date1, date2) 
dt1 = new Date(date1);
dt2 = new Date(date2);
return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - 
                   Date.UTC(dt1.getFullYear(), dt1.getMonth(),dt1.getDate())) / (1000 * 60 * 60 * 24))

How can I iterate through the array to find the days between the dates and sum them up for a total count of days?

Answer №1

Utilize a custom function, like calculateDates, to handle all the necessary calculations for you. In this scenario, its purpose is to determine the number of days between two specified dates.

Next, iterate through your array of startDates and invoke the function within the loop.

Use totalDays += days to keep track of and calculate the overall total number of days.

var calculateDates = function(date1, date2) {
  var dt1 = new Date(date1);
  var dt2 = new Date(date2);
  return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate())) / (1000 * 60 * 60 * 24));
}

var startDate = ["10 Jan 1982", "05 Mar 1990", "28 Dec 2001"];
var endDate = ["25 Jan 1982", "06 Mar 1990", "02 Jan 2002"];

var totalDays = 0;

for (var i = 0; i < startDate.length; i++) {
  var days = calculateDates(startDate[i], endDate[i]);
  console.log("Number of days between", startDate[i], "and", endDate[i], "is", days);
  totalDays += days; 
}

console.log("Total number of days:", totalDays);

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

What steps can be taken to make sure that my Ajax request has completed before executing a new function within the window.onload event

Looking for solutions using plain vanilla JavaScript only, as I do not utilize Json or jQuery currently (I have come across several solutions on SE, but they all involve jQuery or Json). There are two functions within a window.onload=function(){... event ...

Modifying the default value setting in MUI Datepicker

Currently, I am utilizing version @mui/x-date-pickers ^6.17.0. Here is the custom date picker I am using: https://i.stack.imgur.com/k8nF1.png Upon clicking the input field, the placeholder switches and a value gets appended. However, modifying the input ...

unable to assign value to `visibility` or `display` properties

I am having an issue with a dropdownlist box in the datagrid that I need to hide or show. I can retrieve the element, but when I try to hide it, I encounter an error 'Unable to set property 'display' of undefined or null reference.' I h ...

Error in Next.js: Trying to destructure an undefined object in useContext

While attempting to change the state of my cursor in a Next.js app using useContext, I encountered the following error: TypeError: Cannot destructure 'Object(...)(...)' as it is undefined. The goal is to update the state to isActive: true when h ...

Having trouble with your jQuery code not loading properly?

Currently working on debugging jQuery code and facing an issue where a particular section of the code is not being triggered upon clicking. The HTML/PHP in question: $cartlink .= "<a class='add_to_cart button' data-id='{$product->id} ...

Utilizing orbital mechanics for a celestial system visualization in Three.js with coordinates (x,y,z) for planetary bodies

Currently, I am developing a Solar System visualization in Three.js. While my planets currently have basic circular orbits, my goal is to create a realistic model. Despite researching information on wiki and other articles, the content is quite advanced fo ...

axios replicates the URL within the interceptor

I am currently using Axios for my HTTP requests, and I have encountered an issue for the first time. The initial request goes through smoothly, but on the second request, Axios is inexplicably duplicating my URL. The URL that Axios is attempting to fetch ...

Is there a quick way in ES6 to assign member functions as event listeners?

This question is unique and not a repetition of the query posed in How to access the correct `this` context inside a callback? Although some answers may overlap, the Question at hand differs. The comments below the answers indicate varied solutions, parti ...

Running tasks in the background with Express.js after responding to the client

Operating as a basic controller, this system receives user requests, executes tasks, and promptly delivers responses. The primary objective is to shorten the response time in order to prevent users from experiencing unnecessary delays. Take a look at the ...

Sending an array as an extra in an Android intent

Recently, while browsing through the Bundle class documentation, I came across the methods putStringArray(String key, String[] value) and public String[] getStringArray (String key). Although they have been available since API level 1, I had always belie ...

Invoke a "local" function inside module.exports in Node.js

What is the correct way to call a function from within another function in a module.exports declaration? In my MVC structured Node.js project, I have a controller named TestController.js. When trying to access a method within the controller using the this ...

Node.js server crashes upon automatic startup but remains stable when started manually

Currently, I am using Node.js and Socket.io to power an online chat feature. To manage the server, I have created a configuration file located at: /etc/init/example.conf The contents of this file are as follows: start on startup exec forever start /var/ ...

Using jQuery to access OSM data through Overpass API: A step-by-step guide

My current approach to fetch map data from OSM involves the following code: $.ajax({ url: 'https://www.overpass-api.de/api/interpreter?' + '[out:json][timeout:60];' + 'area["boundary"~"administrative" ...

Generating a pool of p_threads

Currently, I'm delving into the realm of threads in C programming. My goal is to create an array of pthread structures that will each execute a function and then be joined together. To achieve this, I followed these steps: 1. Declare a pointer to an ...

Efficiently passing multiple files with Rails using jQuery/Ajax and API

I'm currently utilizing the FileStack API along with the filepicker gem in my project. The JavaScript snippet provided below is responsible for parsing a JSON response from the browser and forwarding it to the create action of the Attachment controlle ...

Numpy Error: Incompatible shapes for broadcasting operands (1,99) and (100,)

Trying to assign the value of y as (x × 0.15) + N where N is a 100-element 1D array containing random values chosen from a Gaussian distribution with mean 0.0 and standard deviation 0.5 has been posing challenges due to an error I keep encountering: Val ...

Ways to prevent horizontal scrolling in an image

Currently, I am working on a scrolling animation page that is optimized for mobile devices. One issue I am encountering is when an element is larger than the screen size, such as when an image is wider than the mobile device. In this scenario, the user can ...

Is there a way to apply a blur effect to a div with the contentEditable attribute set

Is there a way to blur or focus out a content editable div using jQuery? I've tried using $(elm).blur() and $(elm).attr('contentEditable', false); ...

Can someone explain how to implement an onclick event for a div element inside an iframe using jquery or javascript?

Understanding the HTML Structure <iframe src="#" scrolling="no" id="gallery-frame"> <div class="gv_filmstrip"> <div class="gv_frame"> <div class="gv_thumbnail current"> <img src="images/grandstand-padang-right/1.jpg"> </d ...

Leveraging Selenium for testing Polymer components and shadow DOM structures

Having trouble using Selenium with elements inside a shadow DOM. Is there a specific method to handle this situation? Any guidance on what I might be doing wrong? Here are the various approaches I've attempted: var webdriver = require('selenium ...