Pages

Tuesday, May 27, 2008

Transform a date into a number of months from a specific offset date

Here is a small algorithm to transform a date into a number of months from a base date. You can for example use this if you need to create a report with numbers places in a column per month starting with the month of a specific date.

The algorithm to transform the date into a month is this:
if (columDate < dateEndYr(offSetDate))
{
column = mthOfYr(columDate) - mthOfYr(offSetDate) + 1;
}
else
{
column = 12 - mthOfYr(offSetDate) + mthOfYr(columDate) +1;
}

And here is a job to illustrate the usage:

static void date2Column(Args _args)
{
Date offsetdate;
Date columDate;
int column;
int counter;
;

offSetDate = 30\09\2008;
columDate = offSetDate;
while (counter <= 11)
{
counter++;
// The actual algorithm -->
if (columDate < dateEndYr(offSetDate))
{
column = mthOfYr(columDate) - mthOfYr(offSetDate) + 1;
}
else
{
column = 12 - mthOfYr(offSetDate) + mthOfYr(columDate) +1;
}
// The actual algorithm <--
print strFmt("Date: %1 Month: %2", columDate, column);
columDate = dateMthFwd(columDate, 1);
}
pause;
}


UPDATE: As you can see from the comments to this post, I could have simply used the following built in function:
intvNo(columDate, offsetDate, IntvScale::YearMonth) + 1

2 comments:

Jan B. Kjeldsen said...

Very clever, but actually this should be a one-liner:

intvNo(columDate, offsetDate, IntvScale::YearMonth) + 1

The Axapta build-in function intvNo comes very handy, when doing column based calculations on dates.

RTFM, theres even more, intvMax, intvNorm and intvName, which may be of occasional use.

Don't take offense by their weird names, they work like a charm.
They even work in good old XAL.Very clever, but actually this should be a one-liner:

intvNo(columDate, offsetDate, IntvScale::YearMonth) + 1

The Axapta build-in function intvNo comes very handy, when doing column based calculations on dates.

RTFM, theres even more, intvMax, intvNorm and intvName, which may be of occasional use.

Don't take offense by their weird names, they work like a charm.
They even work in good old XAL.

Palle Agermark said...

I stand corrected :-)

Thanks for sharing this.