Friday, March 18, 2011

How to calculate date displacements, working with days, months and years.

When working with date displacements in Dynamics Ax, you can use simple mathematics.
For example, go 3 days back can be written out like:

newDate = today() - 3;

It cannot get any easier.
But this is for days.  May be we want to go back in time or into the future, working with full months or years.  And then the number of days in a month comes into picture.  Mmmm

We can use the DateTimeUtil class from Dynamics Ax to achieve this.  Like we saw in the previous post, this class offers all sorts of calculations for the date.  Use AddDays, AddMonths, AddYears to calculate the date after the offset, working with specific period units.  Use negative arguments to go back in time.


I've included a short job, that is sort of an extension to the DateTimeUtil class.
It can calculate date displacements for 3 different period units.

The code:

static void DateDiffA(Args _args)
   date TransDate;

   TransDate Calcdate(date       startDate,
                      Periods    periodQty,
                      PeriodUnit periodUnit)
      TransDateTime TransDateTime=DateTimeUtil::newDateTime(startDate,0);

      switch (periodUnit)
         case PeriodUnit::Day:
            return any2date(DateTimeUtil::addDays(TransDateTime,periodQty));

         case PeriodUnit::Month:
            return any2date(DateTimeUtil::addMonths(TransDateTime,periodQty));

         case PeriodUnit::Year:
            return any2date(DateTimeUtil::addYears(TransDateTime,periodQty));

      throw error(Error::wrongUseOfFunction(funcname()));


   info(strfmt('The calculated date is %1',date2str(TransDate,123,2,2,2,2,4)));

You can use this code as inspiration to create a new method for the Global class, so you can use it all over in Dynamics Ax.

No comments:

Post a Comment