What is the usage of the SQL DATEDIFF function?
The DATEDIFF function is used to calculate the difference between two dates. Its syntax is as follows:
Get the difference between two dates in terms of a specified datepart.
The datepart parameter specifies the date component to be calculated (such as year, quarter, month, day, etc.), and can be one of the following values:
- Calculate the difference in years.
- quarter: calculate differences between quarters
- calculate the difference in months
- day: calculating the difference in dates
- calculate the difference in hours
- minute: calculate differences in minutes
- Calculate the difference in seconds.
The startdate and enddate parameters specify the start and end dates respectively. The DATEDIFF function returns the difference value between the two dates.
Here are a few examples:
SELECT DATEDIFF(year, '2010-01-01', '2020-12-31') AS YearDiff;
-- 输出:10
SELECT DATEDIFF(month, '2020-01-01', '2020-12-31') AS MonthDiff;
-- 输出:11
SELECT DATEDIFF(day, '2020-01-01', '2020-12-31') AS DayDiff;
-- 输出:365
These examples calculate the differences in years, months, and days between two dates.