Thursday 16 January 2014

find the first and last day of month


DateStartMth and dateEndMth in ax 2012

    1.public date dateStartMth(date _date)

    2.client server public static date dateEndMth(date transDate)

Date and UTCDateTime interval for previous month

This code calculates the first and last date of the previous month

static void EP_dateMonthInterval(Args _args)

{
   date            fromDate;
   date            toDate;
   date            baseDate = systemDateGet();
    ;
    toDate      = dateStartMth(baseDate) - 1;
    fromDate    = dateStartMth(toDate);
    info(strFmt("%1 - %2", fromDate, toDate));
}

UtcDateTime version of the same job
static void EP_UtcdateMonthInterval(Args _args)
{
    UtcDateTime     fromDate;
    UtcDateTime     toDate;
    UtcDateTime     baseDate = DateTimeUtil::utcNow();
    ;
    // Remove this month number of days.
    toDate = DateTimeUtil::addDays(baseDate,-(DateTimeUtil::day(baseDate) -1));
    // Add the rest of this days time minus one second.
    toDate = DateTimeUtil::addSeconds(toDate, -(DateTimeUtil::time(toDate)+1));
    // Remove the number of days we are on in
    // the previous month and add one second to
    // get to the first of the month.
    fromDate = DateTimeUtil::addSeconds(DateTimeUtil::addDays(
    toDate, -(DateTimeUtil::day(toDate))), 1);
    info(strFmt("%1 - %2", fromDate, toDate));
}

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));

}

No comments:

Post a Comment