Search code examples
axaptax++dynamics-ax-2012

Using str2date with strings that also contain a time


I have a method which, given an .NET XmlNode containing an ISO 8601 date in the inner text, will convert it to an X++ date object.

if (CLRInterop::isInitialized(childNode))
{
    return str2Date(childNode.innerText(), 321);
}
else return maxDate();

This works great if supplied a string which contains only a date (eg: 2019-03-21), but as soon as a time is also provided in this string (eg: 2019-03-21T00:00:00), it will return nothing.

The easiest fix for this would be just to strip everything past the first 10 characters, but this would break again if for some reason the string only contains 2 characters for the year. Is there a more robust way of handling strings including times in a call to str2date?


Solution

  • I just wrote this job with a bunch of examples. The very first line might be what you want. You can just create this as a new job in AX and then put a breakpoint on the first line and step through each to see what happens, or modify to experiment.

    It looks like your string is standard ISO format, which I cover below various ways too.

    static void DateTimeJob(Args _args)
    {
        // This line looks about what you want
        utcDateTime     utcDateTimeFromString   = DateTimeUtil::anyToDateTime("2019-03-21T00:00:00");
    
        // ISO standard format. You can just assign it directly without quotes
        utcDateTime     utcDateTimeISOFormat = 2019-03-21T00:00:00;
    
        // Misc vars for below
        utcDateTime     utcNow;
        System.DateTime systemDateTime;
        date            dateOnly;
        str             systemDateTimeStr;
    
        // Look at
        // DateTimeUtil::<> // This has all sorts of useful functions
        // str2datetime() // May be useful to you
        try
        {
            // How to go from AX UTC to System.DateTime
            systemDateTime      = Global::utcDateTime2SystemDateTime(DateTimeUtil::utcNow());
    
            // How to go from System.DateTime to AX UTC
            utcNow              = Global::clrSystemDateTime2UtcDateTime(System.DateTime::get_UtcNow());
    
            // How to get ONLY the date portion from a UTC
            dateOnly            = DateTimeUtil::date(utcNow);
    
            // Cast to string for output
            systemDateTimeStr   = systemDateTime.ToString();
    
            // Output a few examples
            info(strFmt("%1, %2, %3",
                        systemDateTimeStr,
                        utcNow,
                        dateOnly));
        }
        catch (Exception::CLRError)
        {
            error(AifUtil::getClrErrorMessage());
        }    
    }