There are many instances when it is necessary to obtain the current date and time from the user's system. This recipe will show you how to get that information.
Create a new codeunit from Object Designer.
Write the following code in the
OnRun
trigger of the codeunit:MESSAGE('Todays Date: %1\Current Time: %2', TODAY, TIME);
Save and close the codeunit.
When you run the codeunit you should see a window similar to the following screenshot:
The TODAY
keyword returns the date from the system clock on the client computer. In Windows, the current system time is usually located at the bottom-right corner of the task bar. The same holds true for the system time which is returned by the TIME
keyword.
The actual date and time returned depends on which version of the NAV client you are using. In the RoleTailored client, the date and time come from the NAV server. In the Classic client, the date and time come directly from the client computer and users will be able to manipulate the system clock to their advantage if they need to. An example could be a time clock application where a user can clock in, change the system time to eight hours later, clock out, and change it back to the original time.
You can also retrieve the system date and time, all at once, using the CURRENTDATETIME
function. The date and time can be extracted using the DT2DATE
and DT2TIME
functions respectively.
Note
For a complete list of date functions, search the C/SIDE Reference Guide under the Help menu for date and time functions.
The ChangeLog
is a base NAV module that allows you to track changes to specific fields in tables. The following code can be found in Codeunit 423, Change Log Management, in the InsertLogEntry()
method.
ChangeLogEntry.INIT; system timeevents, loggingChangeLogEntry."Date and Time" := CURRENTDATETIME; ChangeLogEntry.Time := DT2TIME(ChangeLogEntry."Date and Time");
Here, instead of using the WORKDATE
function, we use the CURRENTDATETIME
function and then extract the time using the DT2TIME
function. The system designers could have just done the following setup:
ChangeLogEntry.Date := TODAY; ChangeLogEntry.Time := TIME;
The advantage of using CURRENTDATETIME
over TODAY
and TIME
is minimal. CURRENTDATETIME
makes one request to the system, while the second method makes two. It is possible that another operation or thread on the client machine could take over between retrieving the date and time from the computer, however, this is very unlikely. The operations could also take place right before and after midnight, generating some very strange data. The requirements for your modification will determine which method is suits best, but generally CURRENTDATETIME
is the correct method to use.