tags:

views:

162

answers:

2

I have the following sql statement:

start_time = ADDDATE(start_time, INTERVAL $minuteDelta MINUTE), 
end_time   = ADDDATE(end_time, INTERVAL $minuteDelta MINUTE)

start_time and end_time are both time fields in my database (not datetime)

$minuteDelta is 60 for argument's sake

Right now it doesn't throw an error but resets my time fields to 00:00:00. Shouldn't this work? ADDTIME doesn't work because it doesn't accept an interval which is what my jQuery plugin is giving me (an interval). start_time and end_time have some value like 14:00:00 let's say.

I have a similar statement where I'm adding days to a date and it works fine. What's my problem here folks?

EDIT

Entire query

UPDATE events 
    SET start_date = DATE_ADD(start_date, INTERVAL 0 DAY), 
        end_date = DATE_ADD(end_date, INTERVAL 0 DAY), 
        start_time = ADDDATE(start_time, INTERVAL 60 MINUTE),
        end_time = ADDDATE(end_time, INTERVAL 60 MINUTE) 
    WHERE id='1'
+1  A: 

Try this:

$secondDelta = $minuteDelta * 60;

start_time = ADDTIME(start_time, SEC_TO_TIME($secondDelta)),
end_time = ADDTIME(end_time, SEC_TO_TIME($secondDelta))
danielrsmith
This is produces the correct result but there's a typo in your answer. Remove the SELECT in both lines and it's good to go. Thanks @danielrsmith!
jeerose
Good call, not sure why I put SELECT there in the first place!
danielrsmith
+1  A: 

The problem is that ADDDATE requires a full date and time as a parameter, otherwise there is no context for the addition. Passing just a 01:23:45 string/time value as the first parameter gives a warning ("truncated incorrect datetime value") and truncates it to NULL. What happens if you have a time of '23:59:59' and try to add time to it? It can roll over, but what's the context now? Have you gained a day? Does it reset to zero? There's too much ambiguity in a calculation like that.

Anyhow, there doesn't seem to be a function that will produce what you want. I think the closest you're looking at is SEC_TO_TIME and TIME_TO_SEC. You can do something like this:

SELECT SEC_TO_TIME(TIME_TO_SEC('23:30:00') + 60);
-- returns 23:31:00

If you run into a rollover scenario here however, you end up with times greater than a 24 hour clock:

SELECT SEC_TO_TIME(TIME_TO_SEC('23:59:30') + 60);
-- returns 24:00:30

You could probably adjust for that with a rollover by subtracting 86400 from the result of SEC_TO_TIME if it was > 86400. Something like this:

SELECT IF(
    TIME_TO_SEC('23:54:30') + 60 > 86400,
    SEC_TO_TIME(TIME_TO_SEC('23:54:30') + 60 - 86400),
    SEC_TO_TIME(TIME_TO_SEC('23:54:30') + 60)
);
zombat