Home >Database >Mysql Tutorial >How to Add Two Hours to the Current Time in a MySQL Query?

How to Add Two Hours to the Current Time in a MySQL Query?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 14:27:10515browse

How to Add Two Hours to the Current Time in a MySQL Query?

Extending Time by Two Hours in MySQL

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.

Original Query

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

Syntax Error

However, this syntax is invalid in MySQL. The now() function returns a timestamp, and directly adding hours to it is not supported.

Corrected Query

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.

Additional Notes

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn