2016-01-13 88 views
0

我知道这是使用JavaScript库完成的。目前,我已经找到了CRM 2011年唯一的例子包括计算年龄年才使用此代码:如何根据出生日期在Microsoft 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()); 
} 
} 

我需要实现类似的功能也占个月的帮助。

- 谢谢你

+0

为一个月,你的意思,例如:“23.年7个月大“? –

+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?

+0

这应该做到! –

+2

这给了不正确的结果: 举例: 的currentdate:2017年2月2日 生日:1994年2月25日 返回 23年0个月12天..... 应该是 22年11个月9天 – scoob