Friday, February 25, 2011

How to get the first and the last day of a month

When working with dates for a range in a SQL select statement, you may be in need for the first and the last day of a certain month.  What at first seems a bit difficult to calculate (not all the months have the same number of days for example), is pretty easy to accomplish with the right tools.

 
The first day of a month

 
You can fool around with things like mkdate, so something like this:

 
static void FirstOfMonth(Args _args)
{ 
   TransDate TransDate=today();
   TransDate FirstOfMth;
   ;

   FirstOfMth=mkdate(1,mthofyr(TransDate),year(TransDate));

   info(date2str(FirstOfMth,123,2,2,2,2,4));
} 
 
But there is a readily available function in the Global class, albeit somewhat hidden: DateStartMth.
 
So your code could read like this:
 
static void FirstOfMonth(Args _args) 
{
   TransDate TransDate=today();
   TransDate FirstOfMth;
   ;
   FirstOfMth=DateStartMth(TransDate);

   info(date2str(FirstOfMth,123,2,2,2,2,4));
} 

 
The last day of a month

 
Just like with the first day of a month, we have a function that will do the job for us: endmth
This function calculates the last date in the month of the date specified.

static void LastOfMonth(Args _args)
{
   TransDate TransDate=today();
   TransDate LastOfMth;
   ;

   LastOfMth=endmth(TransDate);

   info(date2str(LastOfMth,123,2,2,2,2,4));
}
 
You may want to check out following functions as well, with some other date functionality:

13 comments:

  1. And not to mention:
    dayOfMth()
    dayOfYr()
    wkOfYr()
    mthOfYr()

    :-)

    ReplyDelete
  2. Subscribe to learn this new technique in Ax . Give like comments and share
    https://youtu.be/8dXjRzSk910

    ReplyDelete