NIrik Shan
NIrik Shan

Reputation: 25

Calculate time ago in php

I am trying to create active time ago of users. In every 1 minutes time will be updated in database. Where " $dbtime " is time that is updated in database. This is the the code that I tried but it calculate correctly up to 30 minutes only. I am trying to create up to year. Time kept in database and current time format are same. Please help me to solve this code.

   $now = new datetime('now');
   $current_time = $now->format('yjgis');

   $my_tim  = $current_time - $dbtime;

switch ($my_tim) {
    case $my_tim < 60 && $my_tim > 0:
       $a_tim = "Online";
       break;
    case $my_tim > 60 && $my_tim < 3600 :
       $a_tim = round($my_tim/60) .' '."Min ago";
       break;
   case $my_tim > 3600 && $my_tim < 86400:
      $a_tim =  round(round($my_tim/60)/60).' '."Hour ago";
      break;
   default:
     $a_tim =  "Offline";
}

Upvotes: 0

Views: 50

Answers (1)

Agu Dondo
Agu Dondo

Reputation: 13569

You could use this function extracted from CSS Tricks:

<?php

function ago($time)
{
   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");

   $now = time();

   $difference     = $now - $time;
   $tense         = "ago";

   for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
       $difference /= $lengths[$j];
   }

   $difference = round($difference);

   if($difference != 1) {
       $periods[$j].= "s";
   }

   return "$difference $periods[$j] 'ago' ";
}

echo ago($dbtime);

?>

Upvotes: 1

Related Questions