3
votes

Basically i'm getting time difference between current time and database time.

  $cur_time = time();
  $db_time = $rs[$k]['update_time'];
  $diff = abs($cur_time - $db_time);

  $months  = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); 
  $days    = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
  $hours   = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60)); 
  $minutes  = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60); 
  $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));

Then to display the time diff in minutes, hours, days etc

if($hours!= 0)
  {
        if($hours== 1)
        {
            $time2 = $hours.' hour, ';
        }
        else
        {
            $time2 = $hours.' hours, ';
        }

  }
  else
  {
        $time2 = '';
  }
  if($minutes!= 0)
  {
        if($minutes== 1)
        {
            $time3 = $minuts.' minute, ';
        }
        else
        {
            $time3 = $minuts.' minutes, ';
        }

  }
  else
  {
        $time3 = '';
  }

same for seconds, days and months .. Then to display total time difference,

$timediff = $time1.$time2.$time3.$time4.' ago';

If my minutes is greater than 50 , I need to show message else another message.

if($time3 > 50 || $time4 > 1 || $time3 > 1 || $time2 > 1 || $time1 > 1)
{
    $msg = 'greater';
}
else
{
    $msg = 'lesser';
}

Problem is - Minutes, Hours, days are stored in seperate variable. For suppose, if my time difference is 55 minutes, which is showing

55 minutes ago

my condition is going to if condition which is correct. And if my time difference is 1 hour 2 minutes

 1 hour 2 minutes ago

my condition is again going to if condition considering only 2 minutes which is lesser than 50 min, rather it should go to else loop. How to put conditions for these time differences

2
There is no such thing as an if loop.Oswald
Why don't you work with timestamps?Beat
I'd say that an if statement checks whether the if condition holds and either executes the if branch or (if one exists) the else branch.Oswald

2 Answers

4
votes

Why don't you put your condition before conversion?

$cur_time = time();
$db_time = $rs[$k]['update_time'];
$diff = abs($cur_time - $db_time);

if($diff > 3000) // 3600 is 1 hour and 3000 is 50 minutes
{
     $msg = 'greater';
}
else
{
     $msg = 'lesser';
}

Even if the time difference is 1 hour 2 minutes , this works fine

4
votes

You can use the DateTime class from PHP:

$dt = new \DateTime('@1434438947'); //unix timestamp
$diff = $dt->diff(new \DateTime(), true);

echo $diff->days * 1440 + $diff->h * 60 + $diff->i; //minutes difference absolute