Here is my code I am using to find out the month difference.
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;
});
});
2
Answers
Yes, you guys are great. thank for the suggestions, i have resolved the issue by the same rule suggested by Jonas webe, but not used the moment. Thank you Guys
I am assuming you are looking for the number of first saturdays of the months between two dates.
When working with time, it is best to use an existing library (because time is a programmers worst enemy). I would choose moment and write a function like this:
Functionality of the used functions:
.date(1)
: Sets the day of the month to the first (ref).day(6)
: Sets the date to the next (or current) saturday (ref).add(1, 'month')
: Adds 1 month to the date (ref)