Showing posts with label date. Show all posts
Showing posts with label date. Show all posts

Tuesday, November 11, 2014

How to convert a wrong date

Standard str2date function tries to fix a wrong date. For example, if we got as a parameter fantastic June 31th, it returns us June 30, which can be a bad result for your business case.



There are at least two possible solutions for that.

First, by converting the result back to a string and comparing it with the initial string.

private container cgiValidateDate(str _dateStr)
{
    date                retDate     = str2Date(_dateStr, #cgiDateFormat);
    boolean             isOK        = true;
    str                 madeDateStr = date2StrUsr(retDate, DateFlags::FormatAll);

    if(retDate == dateNull() || _dateStr != madeDateStr)
    {
        error(strFmt("Date %1 is incorrect", _dateStr));
        isOK = false;
    }

    return [isOK, retDate];
}


Second, by using .Net function tryParse.


private container cgiValidateDate(str _dateStr)
{
    date                retDate;
    utcDateTime         retDateTime;
    boolean             isOK        = true;
    
    if(!System.DateTime::TryParse(_dateStr, byref retDateTime))
    {
        error(strFmt("Date %1 is incorrect", _dateStr));
        isOK = false;
    }
    else
    {
        retDate = DateTimeUtil::date(retDateTime);
    }
    return [isOK, retDate];
}


Happy date converting!

Tuesday, December 13, 2011

Dates In An Extended Query Range

Let's say we need to range all the BOM versions that are active as of today. For this purpose we can use an extended range in the query.

{
    QueryBuildRange qbr;
    ;
    if(!_args.record())
        return;
    // there is an active caller!
    switch (_args.record().TableId)
    {
        case tablenum(InventTable):
            inventTable = element.args().record();
            this.query().dataSourceTable(tablenum(InventTable)).addRange(fieldnum(InventTable, ItemId)).value(inventTable.ItemId);
            qbr = this.query().dataSourceTable(tablenum(BOMVersion)).addRange(fieldnum(BOMVersion, RecId));
            qbr.value('(fromDate <= '+date2StrXpp(today())+') && (toDate >= '+date2StrXpp(today())+')');
            break;

The final SQL query will look like this (a fragment):


= BOMVersion.ItemId AND ((Active = 1)) AND (((fromDate <=13\12\2011) && (toDate >= 13\12\2011))) JOIN * FROM BOM(BOM_1) ORDER BY BOM.LineNum ASC ON BOMVersion.BOMId = BOM.BOMId

The idea was taken from the AX forum (in Russian).