getting the month difference based on three dates criteria

here is my code which i am using to find out the month difference, please help me out.
loan disbursement date = 05-12-2023,
loan collection day = 1st saturday of each month
current date
so we need to find out how many 1st saturday falls in between the disbursement date and current date. because on each month 1 saturday they will collect emi

$(document).ready(function () {
  initializeDateInputs();
  // Function to calculate attendance percentage
  function calculateAttendancePercentage() {
    var checkedCount = $('input[name="pstatus[]"]:checked').length; // Count of checked checkboxes
    var totalRowCount = $('#lcount').val(); // Total row count

    // Calculate the percentage of checked checkboxes
    var checkedPercentage = (checkedCount / totalRowCount) * 100;

    return checkedPercentage;
  }

  // Function to update submit button state based on attendance percentage
  function updateSubmitButton() {
    var attendancePercentage = calculateAttendancePercentage();

    if (attendancePercentage >= 50) {
      $('#submit').prop('disabled', false);
    } else {
      $('#submit').prop('disabled', true);
    }
  }

  // Initial calculation and button state update
  updateSubmitButton();

  // Event listener for attendance checkboxes change
  $('input[name="pstatus[]"]').change(function () {
    updateSubmitButton();

    var checkedPercentage = calculateAttendancePercentage();

    // Show toast messages based on attendance percentage
    if (checkedPercentage >= 50) {
      Swal.fire({
        toast: true,
        position: 'top-right',
        showConfirmButton: false,
        timer: 5000,
        icon: 'success',
        title: 'Scheduled Meeting',
        text: 'You have reached 50% attendance requirement. You can now submit the form.',
        customClass: {
          background: 'bg-green', // Apply bg-green class for success
        },
      });
    } else {
      Swal.fire({
        toast: true,
        position: 'top-right',
        showConfirmButton: false,
        timer: 5000,
        icon: 'error',
        title: 'Scheduled Meeting',
        text: 'Please ensure at least 50% attendance to submit the form!',
        customClass: {
          background: 'bg-danger', // Apply bg-green class for success
        },
      });
    }
  });

  // Calculate arrear demand when EMI date changes
  calculateArrearDemand();

  async function calculateArrearDemand() {
    const disdateValue = $("#disdate").val();
    const lrddateValue = $("#lrd").val();

    if (!disdateValue) {
      console.error("Disbursement date is not defined");
      return;
    }

    if (!lrddateValue) {
      console.error("Loan repayment day is not defined");
      return;
    }

    const disbursementDate = parseDate(disdateValue);
    const currentDate = new Date();

    if (!disbursementDate || !currentDate) {
      console.error("Invalid disbursement date or current date");
      return;
    }

    const monthDifference = calculateMonthsDifference(disbursementDate, currentDate, lrddateValue);
    
    console.log("Month difference:", monthDifference);
  }

  // Calculate the difference in months based on disbursement date, current date, and loan repayment day
  function calculateMonthsDifference(disdate, currentDate, lrddate) {
    let monthDifference = 0;
    let currentMonth = disdate.getMonth();
    let currentYear = disdate.getFullYear();
    
    while (currentYear < currentDate.getFullYear() || (currentYear === currentDate.getFullYear() && currentMonth <= currentDate.getMonth())) {
      if (containsNthDayOfMonth(currentYear, currentMonth, lrddate)) {
        monthDifference++;
      }

      currentMonth++;
      if (currentMonth > 11) {
        currentMonth = 0; // January
        currentYear++;
      }
    }

    return monthDifference;
  }

  // Check if the specified month contains the nth occurrence of the specified day
  function containsNthDayOfMonth(year, month, lrddate) {
    const [occurrenceStr, dayOfWeekStr] = lrddate.split(' ');
    const occurrence = parseInt(occurrenceStr[0], 10); // e.g., "1st" -> 1
    const dayOfWeek = getDayIndex(dayOfWeekStr); // e.g., "Saturday" -> 6

    if (isNaN(occurrence) || dayOfWeek === -1) {
      console.error("Invalid occurrence or day of week");
      return false;
    }

    let count = 0;
    for (let day = 1; day <= 31; day++) {
      const date = new Date(year, month, day);
      if (date.getMonth() !== month) break; // Stop if we've moved to the next month

      if (date.getDay() === dayOfWeek) {
        count++;
        if (count === occurrence) return true;
      }
    }

    return false;
  }

  function parseDate(dateStr) {
    if (!dateStr) {
      console.error("Invalid date string:", dateStr);
      return null;
    }

    const parts = dateStr.split('-');
    if (parts.length !== 3) {
      console.error("Invalid date format:", dateStr);
      return null;
    }

    return new Date(parts[2], parts[1] - 1, parts[0]);
  }

  function getDayIndex(dayName) {
    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return days.indexOf(dayName);
  }

  // Function to initialize date inputs
  function initializeDateInputs() {
    const disdateInput = document.getElementById('disdate');
    const lrddateInput = document.getElementById('lrd');

    if (!disdateInput || !lrddateInput) {
      console.error("One or more date input elements are missing");
      return;
    }

    const currentDate = new Date();
    console.log("Current date:", formatDate(currentDate));
  }

  function formatDate(date) {
    if (!date) return null;
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${day}-${month}-${year}`;
  }

  // Form submission handling
  $('#formScheduled').on('submit', function (e) {
    e.preventDefault();
    var form = $(this);
    var gid = $("#gid").val();

    if (gid == "") {
      $("#gid").closest('.form-control form-control-sm').addClass('has-error');
      $("#gid").after('<p class="text-danger">Please enter group name!<br></p>');
    } else {
      $("#gid").closest('.form-control form-control-sm').removeClass('has-error').addClass('has-success');
    }

    if (gid) {
      $.ajax({
        url: "AppController/addScheduledMeeting",
        method: "POST",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        dataType: 'json',
        success: function (response) {
          $(".form-control form-control-sm").removeClass("has-error has-success");

          if (response.success == true) {
            Swal.fire({
              icon: "success",
              title: "Good Job!",
              text: "Meeting scheduled Successfully",
              showConfirmButton: false,
              timer: 5000,
            });
            window.location.reload();
          } else {
            Swal.fire({
              icon: "error",
              title: "Oops...",
              text: "An error occurred. Please try again later.",
              showConfirmButton: false,
              timer: 5000,
            });
          }
        },
        error: function () {
          Swal.fire({
            icon: "error",
            title: "Oops...",
            text: "An error occurred. Please try again later.",
            showConfirmButton: false,
            timer: 5000,
          });
        }
      });
    }
    return false;
  });
});

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật