Sometimes it is necessary to retrieve only a part of a date. NAV has built-in functions to do just that. We will show you how to use it in this recipe.
Create a new codeunit from Object Designer.
Add the following global variables:
Name
Type
Day
Integer
Month
Integer
Year
Integer
Write the following code in the
OnRun
trigger of the codeunit:Day := Date2DMY(TODAY, 1); Month := Date2DMY(TODAY, 2); Year := Date2DMY(TODAY, 3); MESSAGE('Day: %1\Month: %2\Year: %3', Day, Month, Year);
Save and close the codeunit.
When you run the codeunit you should see a window like the following screenshot:
The Date2DMY
function is a basic feature of NAV. The first parameter is a date variable. This parameter can be retrieved from the system using TODAY
or WORKDATE
, a hard-coded date such as 01312010D
, or a field from a table such as Sales Header or Order Date.
The second parameter is an integer that tells the function which part of the date to return. This number can be 1
, 2
, or 3
and corresponds to the day, month, and year (DMY) respectively.
NAV has a similar function called Date2DWY
. It will return the week of the year instead of the month if 2
is passed as the second parameter.
Codeunit 5616, Depreciation Calculation, contains functions to calculate depreciation based on start and end dates. In order to correctly calculate these values, you must know some details such as the number of days between two dates and whether or not any of those days is a leap day. It is with these types of operations that date functions like DATE2DMY
are extremely useful. Have a look at the function DeprDays365
in this codeunit.
StartingYear := DATE2DMY(StartingDate,3); EndingYear := DATE2DMY(EndingDate,3); LeapDays := 0; IF (DATE2DMY(StartingDate,1) = 29) AND (DATE2DMY(StartingDate,2) = 2) AND (DATE2DMY(EndingDate,1) = 29) AND (DATE2DMY(EndingDate,2) = 2) THEN LeapDays := -1; ActualYear := StartingYear; WHILE ActualYear <= EndingYear DO BEGIN LeapDate := (DMY2DATE(28,2,ActualYear) + 1); IF DATE2DMY(LeapDate,1) = 29 THEN BEGIN IF (LeapDate >= StartingDate) AND (LeapDate <= EndingDate) THEN LeapDays := LeapDays + 1; END; ActualYear := ActualYear + 1; END; EXIT((EndingDate - StartingDate) + 1 - LeapDays);