61

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.

starball
  • 20,030
  • 7
  • 43
  • 238
someisaac
  • 1,027
  • 1
  • 11
  • 13

6 Answers6

132

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);
informatik01
  • 16,038
  • 10
  • 74
  • 104
RageZ
  • 26,800
  • 12
  • 67
  • 76
53

Try this one

DATE_ADD(datefield, INTERVAL 30 MINUTE)
Cem Kalyoncu
  • 14,120
  • 4
  • 40
  • 62
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')
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
  • 1
    I came here looking for a generic way to add to datetime variables, and only this answer worked for me. – kurast Apr 09 '13 at 14:36
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.

staticsan
  • 29,935
  • 4
  • 60
  • 73
5

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);
Basant Rules
  • 785
  • 11
  • 8
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
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Balaji
  • 37
  • 1
  • 7