The date formula allows us to determine a new date based on a reference date. This recipe will show you how to use the built-in CALCDATE
NAV function for date calculations.
Let's start by creating a new codeunit from Object Designer.
Add the following global variable by navigating to View | C/AL Globals (Alt + V + B):
Name
Type
CalculatedDate
Date
Write the following code into the
OnRun
trigger of the codeunit:CalculatedDate := CALCDATE('CM+1D', 010110D); MESSAGE('Calculated Date: %1', CalculatedDate);
Now save and close the codeunit.
On executing the codeunit, you should see a window similar to the following screenshot:
The CALCDATE()
function takes in two parameters: a calculation formula and a starting date. The calculation formula is a string that tells the function how to calculate the new date. The second parameter tells the function which date it should start with. A new date is returned by this function, so the value must be assigned to a variable.
The following units can be used in the calculation formula:
Unit |
Description |
---|---|
|
Day |
|
Weekday |
|
Week |
|
Month |
|
Quarter |
|
Year |
These units may be different depending on what language version NAV is running under.
You have two options to place the number before the unit. It can either be a standard number ranging between 1 and 9 or the letter C, which stands for current. These units can be added and subtracted to determine a new date based on any starting date.
Calculation formulas can become very complex. The best way to fully understand them is to write your own formulas to see the results. Start out with basic formulas such as 1M + 2W - 1D and move on to more complex ones, such as –CY + 2Q - 1W.
The following code is part of the CalcNumberOfPeriods()
function of the 485
, Business Chart Buffer
table:
"Period Length"::Week: NumberOfPeriods := (CALCDATE('<-CW>',ToDate)- CALCDATE('<CW>',FromDate)) DIV 7;
The preceding code snippet will return the difference between two dates in terms of weeks. <-CW>
will provide a week start date of ToDate
whereas <CW>
will provide a week end day of FromDate
. The difference between the calculated days will be divided by 7 to get the total number of weeks.
For more details on CALCDATE
, visit the following URL:
http://msdn.microsoft.com/en-us/library/dd301368(v=nav.70).aspx
Retrieving the system date and time
Retrieving the work date
Determining the day, month, and year from a given date
The Checking for conditions using an IF statement recipe in Chapter 2, General Development