Working with Time in X++

Working with time is fairly simple in X++. If you are only concerned with time on any calendar day e.g. 09:30 AM, you should be using the TimeOfDay data type. A variable of this type is an integer representing the number of seconds elapsed since midnight.

Initialization

Initialize the time with 09:30 AM as follows:

secondsElapsed = 9 * 60 * 60 + 30 * 60;

Initialize the variable with current time as follows:

secondsElapsed = timeNow();

Boundaries

Valid values are from 0 to 86399, where 0 represents 12:00:00 AM and 86399 represents 11:59:59 PM. Setting a value higher than 86399 is allowed by the compiler however it will not be correctly interpreted.

secondsElapsed = 0;
secondsElapsed = timeMax();

Conversion

A TimeOfDay value can be converted in to string in a variety of ways. Use time2str function to specify the time separator and time format parameters. Use time2strHM to get hours and minutes in 24-hour format. Similarly, use time2strHMS to get hours, minutes and seconds in the string.

info(time2str(secondsElapsed, TimeSeparator::Auto, TimeFormat::Auto));
info(time2StrHM(secondsElapsed));
info(time2StrHMLeadingZero(secondsElapsed));
info(time2StrHMS(secondsElapsed));

Use str2time to convert a string representation of time to a TimeOfDay value.

secondsElapsed = str2time("11:20:56 am");
info(int2str(secondsElapsed));

Calculating elapsed time

Use the timeConsumed function to calculate and display the elapsed time. It takes the Start Time and End Time as integer parameters, calculates the difference and returns a string describing the elapsed time. E.g. elapsed time from 09:30:00 AM to 01:00:15 PM can be determined as follows:

info(timeConsumed(34200, 46815));

Time Consumed

Extracting time from a utcdatetime field

If you want to extract time from a utcdatetime field in the database, see an example below:

select firstOnly createdDateTime from sysUserLog
order by createdDateTime desc
where sysUserLog.UserId == '';
secondsElapsed = DateTimeUtil::time(sysUserLog.createdDateTime);