Home >Database >Mysql Tutorial >How to Add Two Hours to the Current Time in a MySQL Query?
In MySQL, you may encounter the need to manipulate time values in your queries. One common scenario is adding a specific duration to the current time.
The following query attempts to retrieve rows where the start_time field of the courses table is less than the current time offset by two hours:
SELECT * FROM courses WHERE (now() + 2 hours) > start_time
However, this syntax is invalid in MySQL. The now() function returns a timestamp, and directly adding hours to it is not supported.
To correctly add 2 hours to the current time in MySQL, use the DATE_ADD() function:
SELECT * FROM courses WHERE DATE_ADD(NOW(), INTERVAL 2 HOUR) > start_time
The DATE_ADD() function takes two arguments: the timestamp to be modified (in this case, NOW()) and an INTERVAL specifying the duration and unit of time to be added. In this case, INTERVAL 2 HOUR adds two hours to the current time.
The DATE_ADD() function provides versatile date and time manipulation capabilities. It supports various intervals, including days, months, and years. Refer to MySQL documentation for more details on date and time functions.
The above is the detailed content of How to Add Two Hours to the Current Time in a MySQL Query?. For more information, please follow other related articles on the PHP Chinese website!