****Salary type monthly.****
var getDiffDatesSalary = function days_between(date1,date2, monthlyBasic) {
var dateObj1 = new Date(date1);
var month1 = dateObj1.getMonth(); //months from 1-12
var day1 = dateObj1.getDate();
var year1 = dateObj1.getFullYear();
var daysInMonth1 = Date.getDaysInMonth(year1, month1);
var dateObj2 = new Date(date2);
var month2 = dateObj2.getMonth(); //months from 0-11
var day2 = dateObj2.getDate();// days from 1
var year2 = dateObj2.getFullYear();
var daysInMonth2 = Date.getDaysInMonth(year2, month2);
var date1FractionDays = daysInMonth1 - day1;
var date2FractionDays = daysInMonth2 - day2;
var newDate1, newDate2;
if(day1 > 1){
var perDaySalary1 = monthlyBasic / daysInMonth1;
var thisMonthFarctionDaysSalaryForDate1 = perDaySalary1 * date1FractionDays;
month1 += 1; // after calculate fraction this month basic, round month from next
newDate1 = new Date(year1,month1);
}
if(day2 !== daysInMonth2){
var perDaySalary2 = monthlyBasic / daysInMonth2;
var thisMonthFarctionDaysSalaryForDate2 = perDaySalary2 * day2;
month2 -= 1; //after calculate fraction this month basic, round month from previous
newDate2 = new Date(year2,month2);
}
// i want to calculate totalSalaryamount of date ranges
// var totalFractionDaysSalary = thisMonthFarctionDaysSalaryForDate1 + thisMonthFarctionDaysSalaryForDate2;
// var totalMonthsSalay = roundMonths * monthlyBasic;
// var totalSalaryamount = totalFractionDaysSalary + totalMonthsSalay;
};
**
result = thisMonthFarctionDaysSalaryForDate1 + thisMonthFarctionDaysSalaryForDate2 + (roundMonths * monthlyBasic)
result will be getDiffDatesSalary("2016/01/15","2016/03/25", 1000);
516.13+806.45 + 1000 // total: 2322.58
Or/And getDiffDatesSalary("2015/01/15","2016/03/25", 1000) ;
516.13+806.45 + (1000 * 13) // total: 14322.58
Or/And getDiffDatesSalary("2016/01/01","2016/02/29", 1000);
1000* 2 // 2000
**
I suggest to split the task in two sections:
This proposal uses the difference between years, months and days and makes a correction if the day difference is negative. Same day means one day.
function getDays(date1, date2) {
var date1Obj = new Date(date1),
date2Obj = new Date(date2),
totalYear = date2Obj.getFullYear() - date1Obj.getFullYear(),
totalMonth = date2Obj.getMonth() - date1Obj.getMonth(),
totalDay = date2Obj.getDate() - date1Obj.getDate() + 1;
if (totalDay < 0) {
totalMonth--;
totalDay += new Date(date1Obj.getFullYear(), date1Obj.getMonth(), 0).getDate();
}
return 360 * totalYear + 30 * totalMonth + totalDay;
}
function getDiffDatesSalary(date1, date2, salaryPerMonth) {
return getDays(date1, date2) * salaryPerMonth / 30;
}
document.write(getDiffDatesSalary("2016/01/15", "2016/03/25", 1000) + '<br>');
document.write(getDiffDatesSalary("2016/01/31", "2016/02/15", 1000) + '<br>');
document.write(getDiffDatesSalary("2016/03/20", "2016/03/20", 3000) + '<br>');