我已经编写了这个JavaScript函数来计算从日期输入开始的年和月的差异,但是月份不是以“整体”形式计算的,这意味着差异应该在月份前几天相隔1个月计数增量。
目前,它计算2016-05-30和2016-06-02之间的差异为1个月,即使它实际上不等于一个月。我不需要显示天数,但是如果使用这个例子,我希望输出为0个月。
请提供指导。见下面的功能。
$scope.calculateEmploymentPeriod = function(dateString){
var today = new Date();
var startDate = new Date($scope.data.client.date_appointed);
var years_diff = today.getFullYear() - startDate.getFullYear();
var m = today.getMonth() - startDate.getMonth();
var months_count = (years_diff * 12) + m;
if (m < 0 || (m == 0 && today.getDate() < startDate.getDate())) {
years_diff--;
months_count = months_count - (years_diff * 12);
}else if (months_count > 11){
months_count = months_count - (years_diff * 12);
}else if (months_count == 11){
months_count = months_count - (years_diff * 12);
years_diff--;
}
$scope.data.client.employment_duration_years = years_diff;
$scope.data.client.employment_duration_months = months_count;
}
我想通过添加另一个子句来编辑此版本。
答案 0 :(得分:1)
try to put something like this..
else if(m==1 && today.getDate() < startDate.getDate()) {
months_count = months_count - (years_diff * 12) - 1;
}
答案 1 :(得分:1)
$scope.calculateEmploymentPeriod = function(dateString){
var today = new Date();
var startDate = new Date($scope.data.client.date_appointed);
var years_diff = today.getFullYear() - startDate.getFullYear();
var days_diff = today.getDate() - startDate.getDate()
var months_count = today.getMonth() - startDate.getMonth();
if (months_count<0) {months_count+=12;years_diff--}
if (days_diff<0) months_count--;
if (months_count<0) {months_count=0;}
$scope.data.client.employment_duration_years = years_diff;
$scope.data.client.employment_duration_months = months_count;
}