Custom date and time format

I was extending a customization of Dynamics AX when I ran into the following piece of code. It formats the current date and time to something like 20150525_0042.

str dateValue, dateFormat;
 
dateValue   = date2str( systemDateGet(),
                        321,
                        DateDay::Digits2,
                        DateSeparator::None,
                        DateMonth::Digits2,
                        DateSeparator::None,
                        DateYear::Digits4,
                        DateFlags::FormatAll);
 
dateFormat = strFmt(    "%1%2%3",
                        dateValue, '_',
                        subStr( strRem(time2Str(timeNow(), TimeSeparator::Space, TimeFormat::Auto), ' '),
                                0,
                                4));

If I haven’t formatted the code to make it more readable, you would struggle to follow what it does. Even the original developer had the same problem – I already fixed two bugs (!) in this code snippet.

I rather dropped the code completely and replaced it with this:

str formatted = System.String::Format(
                                '{0:yyyyMMdd_HHmm}',
                                DateTimeUtil::newDateTime(systemDateGet(), timeNow()));

Better, isn’t it? It’s not only shorter, more importantly it’s much easier to understand and maintain. It would be even simpler if I used DateTimeUtil::utcNow() instead of keeping the original logic with systemDateGet() and timeNow().

This is just a simple example of how .NET Interop from X++ can make your life easier – the amount of .NET code available for you is huge. In this particular case, I called String.Format() method with a custom date and time format. You can also use custom formats when parsing strings to dates (DateTime.ParseExact()), which is probably even more useful.

One Comment

Leave a Reply

Your email address will not be published.