Recently I got small problem to calculate no of months between two dates. Dynamics Ax 2012 provides a default function which calculates no of intervals between two dates based on enumeration.
int intvNo(date input_date, date ref_date, int func)
You can use it as
noOfIntervals = intvNo(refDate, inputDate, intvScale::Month);
intvScale enumation have two values for months
- Month
- YearMonth
If we provide the intvScale::Month then X++ ignores the year and assumes that month is calculated within one year.
If we provide the intvScale::YearMonth then X++ calculate the number of months between different years. Consider following example.
static void NumberofMonthsbetweenTwodates(Args _args) { date inputDate = str2Date("1/1/2007", 213); date refDate = str2Date("3/1/2009", 213); int noOfMonths,noOfMonthsBetweenYears; ; noOfMonths = intvNo(refDate, inputDate, intvScale::Month); noOfMonthsBetweenYears = intvNo(refDate, inputDate, intvScale::YearMonth); // noOfMonths= intvNo(firstdate,seconddate,IntvScale::Month); print("noOfMonths :"+int2str(noOfMonths) + " ,noOfMonthsBetweenYears :"+int2str(noOfMonthsBetweenYears)); }
Info box will be return like
noOfMonths :2 ,noOfMonthsBetweenYears :26
Some cases above code did not works then used following function.
InfAdjValidation_MX::monthDifference(FromDate _fromDate, ToDate _toDate)
Example is as follow.
FromDate _fromDate = mkDate(1,1,2018);
ToDate _toDate =mkDate(31,1,2018);
info(int2str( InfAdjValidation_MX::monthDifference( fromDate, toDate)));