OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

getting the month difference based on three dates criteria

  • Thread starter Thread starter deepakparam
  • Start date Start date
D

deepakparam

Guest
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


Code:
$(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;
  });
});

<p>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</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(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;
});
});</code></pre>
</div>
</div>
</p>
 
Top