1

我有两种类型的日期月份明智如何计算 javascript 示例中的经验:2013 年 7 月到 2013 年 3 月

// Assumes Date From (df) and Date To (dt) are valid etc...
var df= new Date("01/15/2010");
var dt = new Date("02/01/2012");   
var allMonths= dt.getMonth() - df.getMonth() + (12 * (dt.getFullYear() -     df.getFullYear()));
var allYears= dt.getFullYear() - df.getFullYear();
var partialMonths = dt.getMonth() - df.getMonth();
if (partialMonths < 0) {
allYears--;
partialMonths = partialMonths + 12;
}
var total = allYears + " years and " + partialMonths + " months between the dates.";
var totalMonths = "A total of " + allMonths + " between the dates.";
console.log(total);
console.log(totalMonths);  


return {jaren: allYears, maanden: partialMonths};
4

1 回答 1

3

将所有内容转换为月份并减去它们。然后除以 12。除以年数,余数为经验月数。像这样的东西:

var startMonth = df.getFullYear() * 12 + df.getMonth();  
var endMonth = dt.getFullYear() * 12 + dt.getMonth();
var monthInterval = (endMonth - startMonth);

var yearsOfExperience = Math.floor (monthInterval / 12);
var monthsOfExperience = monthInterval % 12;
于 2013-10-31T11:40:23.043 回答