Skip to main content
Participant
February 9, 2023
Question

count days between 2 dates

  • February 9, 2023
  • 1 reply
  • 412 views

Hi, I am trying to make a form that will count the number of days between 2 dates and will exclude the public holidays and weekends from the counter.

here is my code wich works fine to exclude the weekends but does not cut the public holidays. (i added 03/01/2023 ad my holiday) 

var start = this.getField("start_date").value;
var end = this.getField("end_date").value;
var start = util.scand("dd/mm/yyyy H:MM:SS", start + " 0:00:01");
var end = util.scand("dd/mm/yyyy H:MM:SS", end + " 23:59:59");
var millisecondsPerDay = 86400 * 1000;
var holidayArray = [util.scand("dd/mm/yyyy H:MM:SS", "01/01/2023 0:00:01"),
util.scand("dd/mm/yyyy H:MM:SS", "03/01/2023 0:00:01"),
util.scand("dd/mm/yyyy H:MM:SS", "03/01/2023 23:59:59"),
util.scand("dd/mm/yyyy H:MM:SS", "30/12/2029 23:59:59")];
event.value = dateDifference(start, end, holidayArray);
function dateDifference(start, end, holidayArray) {
var startDate = new Date(+start);
var endDate = new Date(+end);
var diff = endDate - startDate;
var days = Math.round(diff / millisecondsPerDay);
var weeks = Math.floor(days / 7);
var days = days - (weeks * 2);
var startDay = start.getDay();
var endDay = end.getDay();
if (startDay - endDay > 1) {
days = days - 2;
}
if (startDay == 0 && endDay != 6) {
days = days - 1;
}
if (endDay == 6 && startDay != 0) {
days = days - 1;
}
for (var i = new Date(startDate); i <= endDate; i.setDate(i.getDate() + 1)) {
var currentDay = i.getDay();
if (currentDay == 0 || currentDay == 6) {
continue;
}
for (var j = 0; j < holidayArray.length; j++) {
var holiday = holidayArray[j];
if (i.getTime() === holiday.getTime()) {
days--;
break;
}
}
}
return days;
}

Could anyone help?

This topic has been closed for replies.

1 reply

try67
Community Expert
Community Expert
February 9, 2023

I would change the holiday array to include just strings (instead of Date objects), and with only the date part, not a time notation. That would make the comparison much more reliable.

Participant
February 17, 2023

Thank you, i will try as you sugested.