Hi, I am new to d365fo/ AX,
How to calculate Age of a person in Months from Birth Date.
My need is,
If Age of a person is less than a month, then month should be 0.
If Age of a person is more than a month but less than year, then month should be 1-12.
If Age of a person is more than a month & year, then month should be accordingly.
I would do something like this:
System.DateTime birthDate = 1\6\2023; // For testing
System.DateTime currentDate = DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());
int yearDiff = currentDate.Year - birthDate.Year;
int monthDiff = currentDate.Month - birthDate.Month;
int dayDiff = currentDate.Day - birthDate.Day;
int diffInMonths = yearDiff * 12 + monthDiff + (dayDiff < 0);
Note that I didn’t test it; there may be some issues to fix.
Thanks for the help its working. But in some cases the accuracy is low because of leap years.
If you see a problem that you need to fix but you’re unable to and you need our help, please explain the problem in detail to us.
Okay I did modified your code according to my requirement, and here is my code -
case fieldNum(SH_MC_Vehicle_Master, Registration_Day):
System.DateTime rday = this.Registration_Day;
System.DateTime currentDate = DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());
int yearDiff = currentDate.Year - rday.Year;
int monthDiff = currentDate.Month - rday.Month;
int dayDiff = currentDate.Day - rday.Day;
int diffInMonths = yearDiff * 12 + monthDiff + (dayDiff < 0);
this.Vehicle_Age_In_Months = diffInMonths;
break;
Here my problem is -
I took data like the above pic, and for the date 7/2/2020 - It showing 42 months, where as for the date 7/3/2020 - It showing 43 months.
According to the calculations, it need to show that
for the date 7/2/2020 - It should be 42 months and for the date 7/3/2020 - It should be 41 months , 30 days , But As for it I need only months, so it should be like 41 months. And for the date 7/4/2020 - It should be 41 months , 29 days , But As for it I need only months, so it should also be like 41 months.
Do I understand correctly that you want to completely ignore days? If so, simply remove all code related to days. Strictly speaking, ignoring days will decrease accuracy, but the most important thing is your business requirement. There is no single correct way to calculate months, therefore use whatever makes sense for your particular scenario.
Okay I understood, and Thanks for the help.