How to use the MySQL ADDDATE() function
The ADDDATE() function in MySQL is used to add a time/date interval to a date and return a new date. It is useful for calculating future or past dates based on a start date and an interval.
The ADDDATE() function in MySQL is used to add a time/date interval to a date and return a new date. It is useful for calculating future or past dates based on a start date and an interval.
Syntax
The syntax for ADDDATE() is:
ADDDATE(date, INTERVAL expr unit)
Where:
dateis the start date.expris the amount to add.unitis the unit for the amount to add, like ‘DAY’, ‘WEEK’, ‘MONTH’ etc.
Examples
-
Add 10 days to the current date:
SELECT ADDDATE(CURRENT_DATE, INTERVAL 10 DAY);This would return ‘2023-11-19’ with the current date being ‘2023-11-09’.
-
Subtract 5 months from the current date:
SELECT ADDDATE(CURRENT_DATE, INTERVAL -5 MONTH);This would return ‘2023-06-09’.
-
Add 2 years and 3 months to a specific date:
SELECT ADDDATE('2021-05-15', INTERVAL 2 YEAR 3 MONTH);This would return ‘2023-08-15’.
-
Calculate a past date by subtracting days:
SELECT ADDDATE('2023-11-09', INTERVAL -7 DAY);This returns the date ‘2023-11-02’, 7 days before November 9, 2023.
-
Add 3 weeks to a date:
SELECT ADDDATE('2023-10-12', INTERVAL 3 WEEK);This returns ‘2023-11-02’, 3 weeks after October 12, 2023.
Other Similar Functions
Other date/time manipulation functions in MySQL:
DATE_ADD()- Same asADDDATE()SUBDATE()- Subtract intervals from dateDATEDIFF()- Get difference between two datesDATE_SUB()- Same asSUBDATE()
So ADDDATE() provides an easy way to calculate future or past dates by adding and subtracting intervals from dates in MySQL.