user932852
user932852

Reputation: 13

Adding 10 minutes to a date from mysql datetime and comparing it to the time now

I can't figure out how to add 10 minutes to a time I am getting from mysql database the field structure is datetime.

Current code

$nowtime = date('Y-m-d h:i:s');

$timeoflastlogin = $db->gettime();

//ADD 10 MINS TO TIME LAST ATTEMPTED 
$endtime = strtotime('+ 10 minutes', $timeoflastlogin );
//$endtime = date('Y-m-d h:i:s', strtotime('+ 10 minutes', $timeoflastlogin );

This displays " 2011-09-07 13:53:43 < time of last login 2011-09-07 03:56:15 < now time 2611< endtime - this is supposed to be time of last +10 mins "

I cannot work out how to add 10 mins to the time/date from mysql, I need to do this and then set a command to compare the time now and of last login so if it has been 10 minutes I can stop the user trying to login again!

Thanks for your help

Upvotes: 1

Views: 15841

Answers (4)

Marc B
Marc B

Reputation: 360562

You can do it directly in the database:

SELECT DATE_ADD(datefield, INTERVAL 10 MINUTE)
FROM ...

This saves you the PHP overhead of having to re-parse the date string into a time value, do the addition, then re-convert to a string.

Upvotes: 1

Daniel
Daniel

Reputation: 804

Here is how I have done it in the past: Use php's mktime function: http://www.php.net/manual/en/function.mktime.php

This lets you pass in values for day, month, year, etc (which you can pull out of your sql time). If the minutes is greater than 60, it will automatically adjust the hours for you. It will then return a time stamp.

To get this timestamp back into a sql date format, use the date function.

Something kind of like this:

echo date("M-d-Y", mktime($hour, $min + 10, $sec, $month, $day, $year));

You will have to adjust the "M-d-Y" to get the format you want.

Upvotes: 0

Rijk
Rijk

Reputation: 11301

$timeoflastlogin is not a Unix timestamp but a string - so you can't use that as a $now parameter for strtotime. This should work:

$endtime = strtotime('+ 10 minutes', strtotime( $timeoflastlogin ) );

or easier:

$endtime = strtotime( $timeoflastlogin ) + 600; // 10 minutes == 600 seconds

Upvotes: 6

Related Questions