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:

14 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
  3. IELTS Coaching in Dwarka is renowned for its comprehensive and tailored programs, designed to maximize students' performance in the IELTS exam. With a team of highly experienced instructors, the center provides focused training across all four essential skills: Listening, Reading, Writing, and Speaking. Their curriculum is meticulously crafted, offering numerous practice tests and personalized feedback to enhance test readiness. Modern facilities and interactive learning environments create an engaging atmosphere for effective education. Flexible scheduling options accommodate diverse student needs, including working professionals. The center places strong emphasis on building confidence and sharpening communication skills, which are crucial for exam success. Supported by abundant resources and a nurturing learning community, IELTS Coaching in Dwarka prepares candidates to achieve their desired band scores for academic or immigration objectives.
    https://www.dynamichealthstaff.com/ielts-coaching-dwarka

    ReplyDelete