Date diff() Examples
Back to the Main Page
All of these examples assume that the library has been imported as noted in the Documentation.
Substracting one Date from Another
The diff() method of a date allows you to subtract one date from another and return the number of specified date parts between them. The default method ("Actual") returns the number of periods equal to the selected date part (number of 60-minute periods for hours, 24 hour-periods for days, etc).
The "Actual", "Logical" and "Complete" Options
The diff() method provides three distinct methods for determining differences in dates. These variations in these methods are subtle and care should be taken to understand the best method to apply to a given situation. The methods are:
- Actual: The default method and often the method to return the most "common sense" results. For most date parts this method counts only whole periods (24-hour days, 60-minute hours, 7-day weeks, etc). For "month" and "year" this method counts "date-to-date" differences (April 15 to May 15 is "one month" for example).
- Logical: This method results in a difference for any change in the ordinal value of the date part (in other words the precision of the calculation equals the selected date part). While 11pm, Tuesday is only two actual hours difference from 1am, Wednesday there is a one-day logical difference.
- Complete: This method returns differences only for whole, complete instances of the selected date part, ignoring partial periods at either end. This would mean, for example, that 9:30pm to 11:30pm would be only one-complete hours difference (due to the fact that only the 10pm hour is fully within the range).
The best way to understand these options is through examples:
Daylight Savings Time (DST) Considerations
The diff() method, by default, attempts to normalize seemingly nonsensical results due to DST (or the equivalent) changes. This behavior only affects date pairs where one of the two fall outside DST. This behavior can be overridden using the "NormalizeDST" parameter as in the following examples: