I have been working with this code:
var rangesInputRange1 = [
{ startDate: parseDate("15/04/2024"), endDate: parseDate("01/05/2024") },
{ startDate: parseDate("01/06/2024"), endDate: parseDate("30/06/2024") }
];
var rangesInputRange2 = [
{ startDate: parseDate("01/04/2024"), endDate: parseDate("14/04/2024") },
{ startDate: parseDate("01/07/2024"), endDate: parseDate("31/08/2024") }
];
function parseDate(dateString) {
var parts = dateString.split("/");
return new Date(parts[2], parts[1] - 1, parts[0]);
}
function isDateInRanges(date, ranges) {
return ranges.some(function(range) {
return date >= range.startDate && date <= range.endDate;
});
}
function countDaysInRange(startDate, endDate) {
var oneDay = 24 * 60 * 60 * 1000;
return Math.round(Math.abs((startDate - endDate) / oneDay));
}
jQuery('#start-date, #end-date').on('change', function() {
var startDate = parseDate(jQuery('#start-date').val());
var endDate = parseDate(jQuery('#end-date').val());
var daysInRange1 = isDateInRanges(startDate, rangesInputRange1) ? countDaysInRange(startDate, endDate) : 0;
var daysInRange2 = isDateInRanges(startDate, rangesInputRange2) ? countDaysInRange(startDate, endDate) : 0;
var inputRange1 = jQuery('input.checkbox1');
var inputNumber1 = jQuery('input.number1');
var inputRange2 = jQuery('input.checkbox2');
var inputNumber2 = jQuery('input.number2');
inputRange1.prop('checked', daysInRange1 > 0).trigger('change');
inputNumber1.val(daysInRange1).trigger('change');
inputRange2.prop('checked', daysInRange2 > 0).trigger('change');
inputNumber2.val(daysInRange2).trigger('change');
});
jQuery('#start-date, #end-date').trigger('change');
I have succeeded in if #start-date and #end-date are in same rangesInputRange. in this case, the code works fine.
How can I calculate daysInRange if the selected dates are in both rangesInputRange? (example: dates 10/04/2024 to 17/04/2024)
or selected dates are in part in only one rangesInputRange? (example: 28/08/2024 to 03/09/2024).
(date format: dd/mm/YYYY)
2
Answers
Updated code for
countDaysInRange
functionThe
countDaysInRange
function now calculates the number of days in both ranges separately and returns the total number of days calculated for overlapping or in-range periods.Update
Updated Code
I hope this will help.
Here is an alternative solution that will work with any number of date
ranges
. The functioncalc()
calculates the arraydays
that contains the number of says for each range that is touched by the time period entered by the user. For now it is simply printed to the console.