How to use the MySQL ADDTIME() function

The ADDTIME() function in MySQL is used to add a time interval to a time value and return a new time value. It is useful for calculating future or past times based on a start time and a time interval to add.

Posted on

The ADDTIME() function in MySQL is used to add a time interval to a time value and return a new time value. It is useful for calculating future or past times based on a start time and a time interval to add.

Syntax

The syntax for ADDTIME() is:

ADDTIME(start_time, time_interval)

Where:

  • start_time is the initial time value
  • time_interval is the time interval to add, in the format ‘HH:MM:SS’

Examples

  1. Add 2 hours to the current time:

    SELECT ADDTIME(CURRENT_TIME, '02:00:00');
    

    This would add 2 hours to the current time when the function is called.

  2. Add 15 minutes to a time value:

    SELECT ADDTIME('2022-10-21 09:30:00', '00:15:00');
    

    This would return ‘2022-10-21 09:45:00’, 15 minutes after the initial time.

  3. Subtract 1 hour and 30 minutes from a time:

    SELECT ADDTIME('12:00:00', '-01:30:00');
    

    This would return ‘10:30:00’, 1 hour 30 minutes before 12 PM.

  4. Calculate a past time by subtracting minutes:

    SELECT ADDTIME('15:30:00', '-45:00');
    

    This returns ‘14:45:00’, 45 minutes before the initial time.

  5. Add 3 hours and 45 minutes to a time:

    SELECT ADDTIME('09:15:00', '03:45:00');
    

    This returns ‘13:00:00’, 3 hours 45 minutes after the initial time.

Other Similar Functions

Other time manipulation functions in MySQL:

  • TIME_TO_SEC() - Convert time to seconds
  • SEC_TO_TIME() - Convert seconds to time
  • TIMEDIFF() - Subtract two times
  • MAKETIME() - Create time from hour, minute, second

So ADDTIME() provides an easy way to calculate future or past times by adding or subtracting intervals from time values in MySQL.