我编写了这个 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;
}
我想通过添加另一个子句来简单地编辑此版本。
最佳答案
try to put something like this..
else if(m==1 && today.getDate() < startDate.getDate()) {
months_count = months_count - (years_diff * 12) - 1;
}
关于Javascript 使用整月的日期差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37607355/