JavaScript method for calculating the number of days between two dates on a monthly basis

Currently facing a dilemma where I need to determine the number of days between two specific dates selected from a bootstrap daterangepicker on a monthly basis. For example, if we have:

start date = 07/19/2018 
end date  = 09/28/2018

The desired outcome should be:

number of days in 07 = 13 days
number of days in 08 = 31 days
number of days in 09 = 28 days
total number of days = 72 days

Answer №1

A simple, yet slow approach...

var startingDate = new Date('07/19/2018'),
    endingDate = new Date('09/28/2018'),
    temporaryDate;
if (startingDate > endingDate) {
    temporaryDate = startingDate;
    startingDate = endingDate;
    endingDate = temporaryDate;
}

var temporaryDate = startingDate,
    finalDate = new Date(+endingDate + 86400000),
    dateMap = {}, year, month, day, totalDays = 0;
while (+temporaryDate < +finalDate) {
    year = temporaryDate.getFullYear();
    month = temporaryDate.getMonth() + 1;
    day = temporaryDate.getDate();
    if (!dateMap[year]) {
        dateMap[year] = {};
    }
    if (!dateMap[year][month]) {
        dateMap[year][month] = 1;
    } else {
        ++dateMap[year][month];
    }
    temporaryDate = new Date(+temporaryDate + 86400000);
    ++totalDays;
}

for (var year in dateMap) {
    for (var month in dateMap[year]) {
        console.log('number of days in ' + year + '/' + month + ' = ' + dateMap[year][month] + ' days');
    }
}
console.log('total number of days = ' + totalDays + ' days');

console.log(dateMap);
console.log(totalDays);

Answer №2

When it comes to providing a concise solution, I like to follow Jason's lead and offer a shorter version.

let start = new Date("07/19/2018");
let end = new Date("09/28/2018");
let div = new Date(start.getFullYear(), start.getMonth() + 1, 1);
while (end.getFullYear() !== start.getFullYear() || end.getMonth() !== start.getMonth()) {
console.log((div.getTime() - start.getTime()) / (1000 * 3600 * 24));
start = new Date(div.getTime());
div.setMonth(div.getMonth() + 1);
}
console.log((end.getTime() - start.getTime()) / (1000 * 3600 * 24));

To make the solution inclusive, simply add 1 to the end date.

Answer №3

Simply find the difference and convert it to days.

(new Date("09/28/2018").getTime() - new Date("07/19/2018").getTime())/(24*60*60*1000) + 1

Answer №4

If you're looking to calculate the total number of days, this code snippet will do just that.

const startDate = new Date("07/19/2018");
const endDate = new Date("09/28/2018");
const totalDays = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);

For a more granular approach to counting days month by month, you'll need to break down the inputs into date, month, and year components and iterate through each month incrementally until it reaches the end date.

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

Tips for displaying an entire division without altering the position of its content

I am looking to create a pop-up effect for the entire div that includes images, text, and more. However, I have encountered an issue where when I activate the pop-up feature, the position of the content within the div changes. My goal is to have the div zo ...

How to Send jQuery ajax Requests with Multiple Buttons in a PHP Form

My current issue is as follows: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <form id="roomform" action="room.php" method="POST"> <b ...

Problems Arising with Javascript Animation Functionality

I've created a script for an interactive "reel" that moves up or down when clicking on specific arrow buttons. However, I'm encountering two issues: 1) The up arrow causes it to move downward, while the down arrow moves it upward. 2) After exe ...

Tips for dynamically modifying the default keyword in a div using Jquery to apply color

I am attempting to dynamically apply colors to default SQL keywords. For example, when a user enters the words "select * from table" in a div, I want the words select, from, and table to be displayed in blue color while the remaining default words are di ...

Automatically submitting forms without having to refresh the page

I have been searching for answers online, but none of them seem to help me. Additionally, I am struggling to grasp the concept of Ajax. I need everything to happen on a single page without any refreshing until the entire form is submitted. <form id=" ...

Manipulating variables from the main Node.js file within exported Express routes

Currently, I am working on the backend of a home automation program in Node.js with express as my router. The frontend communicates with the backend through about 50 routes that cover various aspects of the program such as querying device states, updating ...

Enhancing webpage styles with AngularJS

Just starting out with AngularJS and eager to get the best approach to tackle this challenge. Describing my dilemma: I have an anchor element that, when clicked, needs to toggle between classes "show-all" and "hide-all" while also updating the styling of ...

Passing an Integer as a string in Swift to Express using Query Strings

I'm currently facing an issue with passing a query string from Swift to Express. I am sending [String: Any] data in the following manner: let params = ["id": 1] The function I'm sending it to is performing the following actions: postSt ...

The React.js navigation bar hamburger menu refuses to close when toggled

Currently, my team and I have developed a react.js application together. The Navbar feature is functioning correctly, except for a small issue. When the Navbar is toggled using the Hamburger menu on a smaller screen, it opens successfully, but the toggle a ...

Changing a list of items with unique identifier keys

I've got add I've got delete now I need to make modifications The add function simply adds to the collection without any organization The delete function is precise, using a key to locate and remove the desired item: addInput = (name) => ...

How can I determine if a value in a JavaScript object is null or empty?

Here is the issue I am facing: I have an array of objects like the one below: [{ "name": "Alex", "code": "05422180283", "pIva": "05422180283", "subCode": null }, { "name": "John", "code": null, "pIva": null, "subCode": "IT" ...

Combining the power of JavaScript with ASP.NET

My goal is to create a link that will change a session variable upon onclick event, like so: <a href="/Index" onclick="<% HttpContext.Current.Session["location"] = location;%>" > <%=location%> </a> However, as the page proces ...

Optimizing memory usage for server-side JavaScript in an express/node.js API

Review I have delved into JavaScript memory management before, and understand the challenges related to circular DOM references. However, I am somewhat uneasy about how this translates to a server-side JavaScript environment like Node.js, especially when ...

Laravel is unable to interpret formData

I've been on a quest to find answers, but so far I'm coming up empty. I'm trying to send file input to a Laravel controller via Ajax, but it seems like the controller can't read the data at all. Here is my Ajax code: let fd = n ...

Automatically showcase images from a directory upon webpage loading

Is there a way to modify my code so that the images from the first directory are displayed on the page when it loads, instead of waiting for a menu option to be clicked? The page looks empty until a menu option is selected, and I would like the images to s ...

Guide to declaring variables using jQuery

Currently tackling a school project, I stumbled upon some online example solutions and managed to decipher most of the code. However, there is one line that has me puzzled. var $newTweet = $('<div class=tweet></div>'); My assumption ...

The disappearing act of Redux state after being added to a nested array

When attempting to update my redux state, I am facing an issue where the state disappears. My approach involves checking for a parentId - if one exists, I insert the payload into the parent's children array. However, if no parentId is provided, I simp ...

The functionality of Node.js middleware is not functioning correctly

My module contains Routes, and I want to verify access before allowing users to proceed. Within the Routes module, there are two routes and two access-check functions that I want to use as middlewares: const checkUser = (req, res, next) => { if (!us ...

What is the best way to manage files in production using Next.js?

I've been working on a Next.js app for file exchange and am looking to deploy it. During development, the app saves dropped files in the root public folder and retrieves them from there using the <a> tag with an href attribute of uploads/{filena ...

What is the best way to retrieve the index and length of an inserted or deleted string within a text area using JavaScript or jQuery?

Is there a way to determine the start and end of a change if a string is inserted or deleted from a textarea (Event)? I am aware of one solution. Save the current string Add an event listener ('change', dosomething); Compare the strings from s ...