-1

First time posting here, I looked for an answer first and could not find one that worked...

I have a code that checks the current time against the recorded time in a database.

$saved = 2015-09-29 11:11:26

$current = 2015-09-29 11:41:00

if (($current - $saved) < 2 minutes) {
// nothing happens
} else {
// set game to complete
}

Obviously my if (()) statement is incorrect, this is what I need help with. Also, I need this script to run every 2 minutes in the background, cron task? No one will every be going to this page checktimes.php.

Happy Coding
  • 2,517
  • 1
  • 13
  • 24
  • *I looked for an answer first and could not find one that worked...* -- did you? – al'ein Sep 29 '15 at 16:53
  • You just posted pseudo-code (at least inside `if` statement). It tells you don't know how to manipulate datetime strings and objects, which could be learned spending some time inside PHP docs and a **bunch** of googled tutorials and SO related questions. Instead, you ask for written code. So... no research efforts. – al'ein Sep 29 '15 at 16:56
  • 1
    possible duplicate of [PHP find difference between two datetimes](http://stackoverflow.com/questions/15688775/php-find-difference-between-two-datetimes) – Sean Sep 29 '15 at 16:57

2 Answers2

1

You need to convert your date into timestamp and then after compare both the date.

 $timestamp_saved = strtotime($saved);

 $timestamp_current = strtotime($current);

 if(($timestamp_current-$timestamp_saved) < (2*60)){
   // nothing happens
 } else {
  // set game to complete
  }
sandeepsure
  • 1,113
  • 1
  • 10
  • 17
0

Another way using DateTime objects could be:

$saved  = DateTime::createFromFormat('Y-m-d H:i:s', '2015-09-29 11:11:26');
$current = DateTime::createFromFormat('Y-m-d H:i:s', '2015-09-29 11:41:00');

$saved_transformed  = date_format($saved, 'YmdHis');
$current_transformed  = date_format($current, 'YmdHis');


if (($current_transformed - $saved_transformed) < 120) {
    echo "nothing!";
} else {
    echo "game complete!";
}
Minority
  • 1
  • 1