crm 2013中按出生日期字段计算年龄



我需要编写一个全局javascript代码,通过生日字段计算年龄,并将函数从不同的javascript文件调用到特定的实体。由于某种原因,在我将实体javascript文件加载到表单后,我收到错误消息"CalculateAge未定义"。

这是我在全局文件中写的:

CalculateAge: function (birthd)
{
    if (birthd == null) {
        return;}
    var today = new Date().getFullYear();
    year1 = birthd.getFullYear();
    return (today-year1);
}

这是我在实体文件中写的内容,我正在加载到表单中:

function onLoad() {
        var birthDate = Xrm.Page.getAttribute("el_birth_date").getValue();
        Xrm.Page.getAttribute("el_age").setValue(CalculateAge(birthDate));
    }
<小时>

我是Javascript新手。。你能帮忙吗?

用于计算年龄的JavaScript代码不正确,它没有考虑月份和日期。正确的版本是这样的:

function CalculateAge(birthday, ondate) {
   // if ondate is not specified consider today's date
   if (ondate == null) { ondate = new Date(); }
   // if the supplied date is before the birthday returns 0
   if (ondate < birthday) { return 0; }
   var age = ondate.getFullYear() - birthday.getFullYear();
   if (birthday.getMonth() > ondate.getMonth() || (birthday.getMonth() == ondate.getMonth() && birthday.getDate() > ondate.getDate())) { age--; }
   return age;
}

并且可以用作:

var birthday = Xrm.Page.getAttribute("new_birthday").getValue();
var age = CalculateAge(birthday);
alert(age);
// age on 1st January 2000, JavaScript Date() object contains months starting from 0
var testdate = new Date(2000, 0, 1, 0, 0, 0);
var testage = CalculateAge(birthday,testdate);
alert(testage);

如果CalculateAge未定义,则可能您没有在表单中包含包含函数的web资源。如果您有两个JS web资源(一个包含函数,另一个包含onLoad事件),则两者都需要包含在表单中。

如果您所在的CRM版本存在异步javascript加载问题,最好将CalculateAge函数与onLoad事件包含在同一个文件中,但如果您喜欢将它们分开,请查看以下博客文章:U12/POLARIS 之后javascript Web资源的异步加载

JavaScript函数来自我的博客文章:在Microsoft Dynamics CRM 2011 中计算年龄

最新更新