adding 30 minutes to datetime php/mysql
Asked Answered
D

6

63

I have a datetime field (endTime) in mysql. I use gmdate() to populate this endTime field.

The value stored is something like 2009-09-17 04:10:48. I want to add 30 minutes to this endtime and compare it with current time. ie. the user is allowed to do a certain task only 30 minutes within his endTime. After 30 minutes of his endTime, they should not be allowed to do a task.

How can this be done in php?

I'm using gmdate to make sure there are no zone differences.

Ducal answered 17/9, 2009 at 5:26 Comment(0)
Q
134

If you are using MySQL you can do it like this:

SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;


For a pure PHP solution use strtotime

strtotime('+ 30 minute',$yourdate);
Quadrangular answered 17/9, 2009 at 5:33 Comment(1)
This is the perfect solution for mysql and php. This should be marked as answer.Ioved
H
53

Try this one

DATE_ADD(datefield, INTERVAL 30 MINUTE)
Hardihood answered 17/9, 2009 at 5:34 Comment(0)
L
7

MySQL has a function called ADDTIME for adding two times together - so you can do the whole thing in MySQL (provided you're using >= MySQL 4.1.3).

Something like (untested):

SELECT * FROM my_table WHERE ADDTIME(endTime + '0:30:00') < CONVERT_TZ(NOW(), @@global.time_zone, 'GMT')
Lightness answered 17/9, 2009 at 5:34 Comment(1)
I came here looking for a generic way to add to datetime variables, and only this answer worked for me.Giantism
B
5

Dominc has the right idea, but put the calculation on the other side of the expression.

SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)

This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.

Bobbysoxer answered 17/9, 2009 at 7:8 Comment(0)
M
5

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);
Monotone answered 15/11, 2016 at 4:45 Comment(0)
E
1

Get date from MySQL table by adding 30 mins

SELECT loginDate, date_add(loginDate,interval 30 minute) as newLoginDate 
FROM `tableName`;

This will result like below

Login Date - 2020-07-22 14:00:00
New Login Date - 2020-07-22 14:30:00
Elecampane answered 21/7, 2021 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.