Name

SUBTIME( )

Synopsis

SUBTIME(datetime, datetime)

This function returns the date and time for the given string or column, decreased by the time given as the second argument (d hh:mm:ss). If a negative number is given, the time is added and the function is the equivalent of ADDTIME(). This function is available as of Version 4.1.1 of MySQL.

SELECT NOW( ) AS Now,
       SUBTIME(NOW( ), '1:00:00.00') AS 'Hour Ago';
+---------------------+---------------------+
| Now                 | Hour Ago            |
+---------------------+---------------------+
| 2005-01-12 00:54:59 | 2005-01-11 23:54:59 |
+---------------------+---------------------+

Notice that the hour was decreased by one, and because the time is just after midnight, the function causes the date to be altered by one day, as well. To decrease the date, add the number of days before the time (separated by a space) like so:

 SELECT NOW( ) AS Now,
        SUBTIME(NOW( ), '30 0:0.0') AS 'Thirty Days Ago';
+---------------------+---------------------+
| Now                 | Thirty Days Ago     |
+---------------------+---------------------+
| 2005-01-12 00:57:04 | 2004-12-13 00:57:04 |
+---------------------+---------------------+

Get MySQL in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.