The ADDTIME() function in MySQL is used to add a time value to a given datetime or timestamp. The function allows you to add a specified time interval (in the form of hours, minutes, and seconds) to a given time or datetime value.
Syntax:
ADDTIME(datetime, time)
- datetime: The starting datetime or timestamp value to which you want to add time.
- time: The time interval you want to add, in the format
HH:MM:SS(hours, minutes, and seconds).
Example 1: Adding time to a datetime value
If you have a datetime value and want to add 3 hours, 15 minutes, and 30 seconds to it, you would use:
SELECT ADDTIME('2024-12-23 10:00:00', '03:15:30');
Output:
+-------------------------------+
| ADDTIME('2024-12-23 10:00:00', '03:15:30') |
+-------------------------------+
| 2024-12-23 13:15:30 |
+-------------------------------+
Example 2: Adding a time interval to the current datetime
You can also add time to the current datetime using the NOW() function. For example, adding 2 hours and 30 minutes to the current time:
SELECT ADDTIME(NOW(), '02:30:00');
Example 3: Adding time to a time value
You can also use ADDTIME() with a time value. For instance, adding 1 hour and 45 minutes to a time:
SELECT ADDTIME('10:15:00', '01:45:00');
Output:
+------------------------------+
| ADDTIME('10:15:00', '01:45:00') |
+------------------------------+
| 12:00:00 |
+------------------------------+
Important Notes:
- The
timeargument can be any valid time format, including negative time intervals (e.g.,'-01:00:00'to subtract time). - The result will be a
DATETIMEorTIMEtype, depending on the type of the first argument.
Example 4: Subtracting time (using a negative time interval)
SELECT ADDTIME('2024-12-23 10:00:00', '-02:00:00');
Output:
+-----------------------------------+
| ADDTIME('2024-12-23 10:00:00', '-02:00:00') |
+-----------------------------------+
| 2024-12-23 08:00:00 |
+-----------------------------------+
In this case, subtracting 2 hours from the datetime value results in 2024-12-23 08:00:00.
Let me know if you need further examples or clarifications!
No comments:
Post a Comment