You often try to calculate the differences between two dates using the available functions in dynamics ax for dates. However, for example I have two dates such as start date = 07/07/2007 and end date = 01/11/2016 where date caculator would show difference like 9 Years 3 Months 25 Day. What if the same detail calculation I have to perform in X++. This post will save your time since we might sometimes require this code during ax programming.
static void AXDateCaculator(Args _args)
{
int monthsDiff, daysDiff, yearsDiff;
date emergingDateMth, emergingDateYear;
str dateCalculated;
//Dates can be changed here
date startdate = mkDate(7, 7, 2007);
date endDate = mkDate(1, 11, 2016);
///
yearsDiff = intvNo(endDate,startDate,IntvScale::Year);
emergingDateYear = DateMthFwd(startDate, yearsDiff*12);
monthsDiff = intvNo(endDate,emergingDateYear,IntvScale::YearMonth);
if (monthsDiff < 0)
{
yearsDiff = yearsDiff - 1;
emergingDateYear = DateMthFwd(startDate, yearsDiff*12);
monthsDiff = intvNo(endDate,emergingDateYear,IntvScale::YearMonth);
}
emergingDateMth = DateMthFwd(emergingDateYear, monthsDiff);
daysDiff = intvNo(endDate,emergingDateMth,IntvScale::MonthDay);
if (daysDiff < 0)
{
monthsDiff = monthsDiff - 1;
emergingDateMth = DateMthFwd(emergingDateYear, monthsDiff);
daysDiff = intvNo(endDate,emergingDateMth,IntvScale::MonthDay);
}
if (yearsDiff)
{
dateCalculated += strfmt(" Years: %1", yearsDiff);
}
if (monthsDiff)
{
dateCalculated += strfmt(" Months: %1", monthsDiff);
}
if (daysDiff)
{
dateCalculated += strfmt(" Days: %1", daysDiff);
}
info(dateCalculated);
}
After you execute this code you will see this result:Happy Daxing :)!