How to subtract 30 days from the current datetime in MySQL?

MySQLMySQLi Database

To subtract 30 days from current datetime, first we need to get the information about current date time, then use the now() method from MySQL. The now() gives the current date time.

The method to be used for this is DATE_SUB() from MySQL. Here is the syntax to subtract 30 days from current datetime.

The syntax is as follows −

DATE_SUB(NOW(),INTERVAL 30 DAY);

The above syntax calculates the current datetime first and in the next step, subtracts 30 days. Let us first seethe query to get the current datetime −

mysql> select now();

Here is the output −

+---------------------+
| now()               |
+---------------------+
| 2018-11-23 16:38:43 |
+---------------------+
1 row in set (0.00 sec)

Now, let us used the date_sub() method to subtract 30 days. The query is as follows −

mysql> select date_sub(now(),interval 30 day);

Here is the output displaying a date after subtracting 30 days −

+---------------------------------+
| date_sub(now(),interval 30 day) |
+---------------------------------+
| 2018-10-24 16:38:50             |
+---------------------------------+
1 row in set (0.00 sec)

To get only the date value in the result, you can use curdate() instead of now(). Here is the demo of curdate().

The query is as follows −

mysql> select date_sub(curdate(),interval 30 day);

The following is the output −

+-------------------------------------+
| date_sub(curdate(),interval 30 day) |
+-------------------------------------+
| 2018-10-24                          |
+-------------------------------------+
1 row in set (0.00 sec)
raja
Published on 21-Dec-2018 12:37:33
Advertisements