0

I am new to javascript.

I have specific month columns (9/30/2022, 10/31/2022,11/30/2022). I have a contract with a start date and end date (spanning multiple months).

I need to determine the number of days the contract was active for a specific month column.

Example:
Contact Start Date: 09/15/2022
Contract End Date: 10/24/2022 Number of days the contract was active in Sept 2022 is 16.

I found the code below that gives me the contract period broken down for each month (i.e.) **9 - 17; 10 - 23; **

Thank you in advance for any assistance.

I found this code

function getDays() {
var dropdt = new Date(document.getElementById("arr").value);
var pickdt = new Date(document.getElementById("dep").value);
var result = "";
for (var year = dropdt.getFullYear(); year <= pickdt.getFullYear(); year++) {
var firstMonth = (year == dropdt.getFullYear()) ? dropdt.getMonth() : 0;
var lastMonth = (year == pickdt.getFullYear()) ? pickdt.getMonth() : 11;
for (var month = firstMonth; month <= lastMonth; month++) {
var firstDay = (year === dropdt.getFullYear() && month === firstMonth) ? dropdt.getDate() : 1;
var lastDay = (year === pickdt.getFullYear() && month === lastMonth) ? pickdt.getDate() : 0;
var lastDateMonth = (lastDay === 0) ? (month + 1) : month
var firstDate = new Date(year, month, firstDay);
var lastDate = new Date(year, lastDateMonth, lastDay);
result += (month + 1) + " - " + parseInt((lastDate - firstDate) / (24 * 3600 * 1000) + 1) + "; ";
        }
    }
return result;
}

function cal() {
if (document.getElementById("dep")) {
document.getElementById("number-of-dates").value = getDays();
    }

Calculate `
Brenda
  • 3
  • 1
  • Here is the link to the original code. https://stackoverflow.com/questions/58743975/count-the-number-of-days-per-month-between-two-dates – Brenda Jan 04 '23 at 18:40
  • This question seems to lack clarity (*as a few users have assumed you want to find the number of days between two dates, but it seems you want a subset of that being the number of those days that fall within a specific month*). You stated "*I have specific month columns (9/30/2022, 10/31/2022,11/30/2022)*" but have provided no HTML or code of your own (*just code from another question/answer*). What does *your* HTML/code look like? How is the user specifying which month to see the days for that active contract? – EssXTee Jan 04 '23 at 19:16

2 Answers2

0

Managing and calculating dates, times, and date-times are notoriously finicky in javascript and across browsers. Rather than trying to define your own logic for this use the famous Moment.js library.

In particular to calculate the length between two dates you can utilize the diff function between two moments

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 25]);
var diff = a.diff(b, 'days') // 1
console.log(diff);
<script src="https://momentjs.com/downloads/moment.js"></script>

The supported measurements are years, months, weeks, days, hours, minutes, and seconds.

Cody
  • 467
  • 2
  • 11
0

The following snippet will generate an object res with the keys being zero-based month-indexes ("8" is for September, "9" for October, etc.) and the values are the number of days for each of these months:

const start=new Date("2022-09-15");
const end=new Date("2022-11-24");
let nextFirst=new Date(start.getTime()), month, days={};
do { 
  month=nextFirst.getMonth();
  nextFirst.setMonth(month+1);nextFirst.setDate(1);
  days[month]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
  start.setTime(nextFirst.getTime());
} while(nextFirst<end)

console.log(days);

This can be extended into a more reliable function returning a year-month combination:

function daysPerMonth(start,end){
 let nextFirst=new Date(start.getTime()), year, month, days={};
 do {
   year=nextFirst.getFullYear(); 
   month=nextFirst.getMonth();
   nextFirst.setMonth(month+1);nextFirst.setDate(1);   
   days[`${year}-${String(1+month).padStart(2,"0")}`]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
   start.setTime(nextFirst.getTime());
 } while(nextFirst<end)
 return days;
}

[["2022-09-15","2022-11-24"],["2022-11-29","2023-02-04"]].forEach(([a,b])=>
 console.log(daysPerMonth(new Date(a),new Date(b))));
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43