Constructing date values

Sometimes you have to construct at date at runtime with part of the date based on user input. Like when you have to summarize transactions for a given year.

Ax has a built-in function for this but all too often I see people resorting to convoluted string conversions to achieve the goal. Please don’t, it’s harder to read, more error prone and less efficient. Use mkDate() instead.

So instead of writing something like this:

static void Job1(Args _args)
{
    int givenYear = 2009; // Value acquired somewhere outside the method
 
    date fromDate, toDate;
    ;
 
    fromDate    = str2date("1/1/" + int2str(2009), 123);
    toDate      = str2date("1/1/" + int2str(2009), 123);
}

Write this:

static void Job1(Args _args)
{
    int givenYear = 2009;  // Value acquired somewhere outside the method
 
    date fromDate, toDate;
    ;
 
    fromDate    = mkDate(1, 1, givenYear);
    toDate      = mkDate(31, 12, givenYear);
}

To me, the most important advantage of mkDate() is clarity. Using string conversions distracts from the actual task of constructing a date. Additionally because all arguments to mkDate() are integers it’s easy to do input validation or build a whole bunch of date values in a loop, e.g. every first of every month.

2 thoughts on “Constructing date values”

Leave a Reply

Your email address will not be published. Required fields are marked *