如何根据 Microsoft CRM 2011 中的出生日期计算年龄(以年和月为单位)

How to calculate age in years and months based on date of birth in Microsoft CRM 2011

我知道这是使用 javascript 库完成的。目前,我为 CRM 2011 找到的唯一示例涉及仅使用以下代码计算年龄:

function CalcAge()
{
var now = new Date(); //Todays Date   
var birthday = Xrm.Page.getAttribute("birthdate").getValue(); //Get the Date of Birth value   
var diff = now.getMonth() - birthday.getMonth();  //Check to see if Birthday  has already passed

if (diff > -1) //If Birthday has already occurred   
{
    var bd1 = now.getFullYear() - birthday.getFullYear();

    //set the age attribute 
    Xrm.Page.getAttribute("frc_age").setValue(bd1.toString());  
}
else //If Birthday has not already occurred  
{
    var bd2 = now.getFullYear() - birthday.getFullYear() - 1;
    Xrm.Page.getAttribute("frc_age").setValue(bd2.toString()); 
}
}

我需要帮助来实现类似的功能,该功能也可以计算月份。

-谢谢

如果 DOB 格式为 "MM/dd/yyyy",您可以尝试以下代码。您也可以相应地更改为其他格式。

var now = new Date(); //Todays Date   
var birthday = Xrm.Page.getAttribute("birthdate").getValue();
birthday=birthday.split("/");   

var dobMonth= birthday[0]; 
var dobDay= birthday[1];
var dobYear= birthday[2];

var nowDay= now.getDate();
var nowMonth = now.getMonth() + 1;  //jan = 0 so month + 1
var nowYear= now.getFullYear();

var ageyear = nowYear - dobYear;
var agemonth = nowMonth - dobMonth;
var ageday = nowDay- dobDay;
if (agemonth <= 0) {
       ageyear--;
       agemonth = (12 + agemonth);
        }
if (nowDay < dobDay) {
      agemonth--;
      ageday = 30 + ageday;
      }
var val = ageyear + "-" + agemonth + "-" + ageday;
return val;

您还可以使用以下一些:

Simple age calculator in JavaScript

Calculate age in JavaScript

javascript - Age calculation

How can I calculate the number of years betwen two dates?