How do you use the DATEADD and DATEDIFF functions to manipulate dates?
Posted by MaryJns
Last Updated: August 02, 2024
In SQL, the DATEADD and DATEDIFF functions are commonly used to manipulate and operate on date values. Below is a detailed explanation of how each function works, along with examples.
DATEADD Function
The DATEADD function is used to add a specified time interval to a date. The syntax is as follows:
DATEADD(datepart, number, date)
- datepart: This specifies the part of the date that you want to add to. Common values include: - year - quarter - month - day - hour - minute - second - number: The number of the specified datepart to add. This can be a positive (to add) or negative (to subtract) integer. - date: The starting date to which the interval is added.
Example:
To add 10 days to the current date:
SELECT DATEADD(day, 10, GETDATE()) AS NewDate;
If you wanted to subtract 5 months from a specific date:
SELECT DATEADD(month, -5, '2023-10-01') AS NewDate;
DATEDIFF Function
The DATEDIFF function calculates the difference between two dates and returns the result as an integer. The syntax is as follows:
DATEDIFF(datepart, startdate, enddate)
- datepart: This specifies the part of the date you want to measure the difference in. The same options as DATEADD apply here (e.g., year, month, day, etc.). - startdate: The start date. - enddate: The end date.
Example:
To calculate the number of days between two dates:
SELECT DATEDIFF(day, '2023-01-01', '2023-10-01') AS DaysDifference;
To find out how many months are between today and a specific date:
SELECT DATEDIFF(month, '2022-01-01', GETDATE()) AS MonthsDifference;
Summary
- Use DATEADD to add or subtract specified time intervals from a date. - Use DATEDIFF to calculate the difference between two dates in terms of a specified datepart. These functions are particularly useful in scenarios involving date comparisons, calculations for reporting, and dynamic date handling in SQL queries.