如何根据Microsoft CRM 2011中的出生日期计算年龄和月份的年龄

时间:2016-01-13 16:48:05

标签: javascript dynamics-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()); 
}
}

我需要帮助实现一个类似的功能,也可以说明几个月。

- 谢谢你

1 个答案:

答案 0 :(得分:1)

如果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?