date_diff function
Applies to: Databricks SQL
Databricks Runtime 13.3 LTS and above
Returns the difference between two dates in days, or between two timestamps in a specified unit.
Syntax
date_diff(endDate, startDate)
date_diff(unit, start, end)
unit
{ MICROSECOND |
MILLISECOND |
SECOND |
MINUTE |
HOUR |
DAY |
WEEK |
MONTH |
QUARTER |
YEAR }
Arguments
endDate: An endingDATEexpression.startDate: A startingDATEexpression.unit: A unit of measure.start: A startingTIMESTAMPexpression.end: An endingTIMESTAMPexpression.
Returns
- For
date_diff(endDate, startDate), anINTEGERthat represents the number of days fromstartDatetoendDate. - For
date_diff(unit, start, end), aBIGINTthat represents the difference betweenstartandendmeasured inunits. This form is a synonym fortimestampdifffunction.
The result is negative if the starting value is greater than the ending value.
The function counts whole elapsed units based on UTC with a DAY being 86400 seconds.
One month is considered elapsed when the calendar month has increased and the calendar day and time is equal or greater to the start. Weeks, quarters, and years follow from that.
Examples
SQL
> SELECT date_diff(DATE'2009-07-31', DATE'2009-07-30');
1
-- One second shy of a month elapsed
> SELECT date_diff(MONTH, TIMESTAMP'2021-02-28 12:00:00', TIMESTAMP'2021-03-28 11:59:59');
0
-- One month has passed even though its' not end of the month yet because day and time line up.
> SELECT date_diff(MONTH, TIMESTAMP'2021-02-28 12:00:00', TIMESTAMP'2021-03-28 12:00:00');
1
-- Start is greater than the end
> SELECT date_diff(YEAR, DATE'2021-01-01', DATE'1900-03-28');
-120