Date Difference (DateDiff)
What is it?
The DateDiff function accepts two date strings and returns the numeric difference between the two. The difference can be measured in days, hours, minutes or seconds depending on the arguments you supply.
What is the Syntax?
The DateDiff function’s syntax is as follows:
DateDiff( FirstDate, SecondDate, DateFormat );
The DateFormat argument is optional; if it is not included, the difference is measured in hours. Otherwise, supplying an integer between 1 and 3 alters the returned difference as follows:
- 1 – measured in days.
- 2 – measured in minutes.
- 3 – measured in seconds.
Why might I want to use this?
The insurance questionnaire discussed in the previous section requires all end users to supply their date of birth. Using this date, we can call the GetDate function and combine it with the DateDiff function to calculate the customer’s age in years. To do this, we nest the functions together as shown below:
AgeInYears := Floor( DateDiff( DateOfBirth, GetDate(), 1 ) / 365 );
Notice we used 1 as the third argument in this expression? This returns the difference between the two dates in days. We then divide the number of days by 365 to get the age in years, and finally execute the Floor function to remove the decimal from the end and round down to the number of whole years.
Although this expression does not take into account the reduced days in a leap year, this can be worked around by expanding the code as follows:
AgeInYears := Floor ( DateDiff( DateOfBirth, GetDate(), 1 ) / 1459 * 4;
Although this is a more accurate measurement, the margin of error when calculating something as small as a person’s age is so low, there is little noticeable difference between the results of the two expressions. When counting a much larger number of years, the second expression would be preferable.
<< Previous: GetDate | Next: Add to Date (DateAdd) >>