Home >Database >Mysql Tutorial >Use MySQL's DATE_ADD function to add and subtract dates
Use MySQL's DATE_ADD function to perform date addition and subtraction operations
Date addition and subtraction operations are often encountered in development, such as calculating dates in the next few days or calculating dates in the past few months. MySQL provides the DATE_ADD function, which can easily add and subtract dates. This article will introduce the basic usage of the DATE_ADD function in detail and give relevant code examples.
Among them, date is to be added The date of the subtraction operation, expr is the value to be added or subtracted, and interval_type specifies the time unit to be added or subtracted.
SELECT DATE_ADD(CURDATE(), INTERVAL 3 DAY) AS future_date;
The output is as follows:
+-------------+ | future_date | +-------------+ | 2021-02-04 | +-------------+
In the above example, CURDATE() gets the current date, and then Use the DATE_ADD function to add it, add 3 days, and get the date three days in the future.
SELECT DATE_ADD(CURDATE(), INTERVAL -5 DAY) AS past_date;
The output is as follows:
+------------+ | past_date | +------------+ | 2021-01-27 | +------------+
In the above example, CURDATE() gets the current date, Then use the DATE_ADD function to subtract it, subtracting 5 days, and get the date five days ago.
Add and subtract months:
SELECT DATE_ADD(CURDATE(), INTERVAL 2 MONTH) AS new_date;
This example means adding 2 months to the current date.
Add and subtract years:
SELECT DATE_ADD(CURDATE(), INTERVAL 1 YEAR) AS new_date;
This example means adding 1 year to the current date.
Add and subtract weeks:
SELECT DATE_ADD(CURDATE(), INTERVAL 3 WEEK) AS new_date;
This example means adding 3 weeks to the current date.
The above is the detailed content of Use MySQL's DATE_ADD function to add and subtract dates. For more information, please follow other related articles on the PHP Chinese website!