Adding time in MySQL

0

I'm trying to add a certain time to another. For example: I have the time: 23:00:00 (11) and I want to add 2 hours (that of 01:00:00) but I do not achieve it.

I tried ADDTIME ("23:00:00", "02:00:00") but this returns me 25?

How could you successfully execute this query?

Thank you very much already.

    
asked by Alejandro 09.12.2017 в 00:06
source

1 answer

1

The problem can be solved in different ways.

In my opinion, the safest way would be:

  • Convert the value 23:00:00 to date, giving it the format %H:%i:%s , because at the end of the day it is just a string. That way you have the value properly controlled and you would act on an object DATETIME .
  • Use INTERVAL , instead of using another string to indicate the hours I want to add.
  • Control the output format with DATE_FORMAT .

Applying the above, we will have then:

Solution 1:

SELECT 
DATE_FORMAT(DATE_ADD(STR_TO_DATE('23:00:00', '%H:%i:%s'),INTERVAL 2 HOUR), '%H:%i:%s') hora;

Exit:

hora
01:00:00

Solution 1 uses DATE_ADD instead of ADDTIME .

Solution 2

It can also be done with ADDTIME , only in that case, you can not use INTERVAL , which, in my opinion, is more accurate than a hardcoded time.

The result will be the same:

SELECT 
DATE_FORMAT(ADDTIME(STR_TO_DATE('23:00:00', '%H:%i:%s'), '02:00:00'), '%H:%i:%s') hora ;

Exit:

hora
01:00:00
    
answered by 09.12.2017 / 01:12
source