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
Release: 2024-12-10 14:27:10
Original
556 people have browsed it

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template