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

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

本文关键字:为单位 计算 出生日期 Microsoft CRM 2011      更新时间:2023-09-26

我知道这是使用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;

你也可以使用下面的一些:

JavaScript 中的简单年龄计算器

在JavaScript 中计算年龄

javascript-年龄计算

我如何计算两个日期之间的年数?