Jump to content

Converting timestamp to a "xx hours xx minutes ago" format, my take


Recommended Posts

function time_ago($timestamp)
{
   //$months = array("Jan" => 31, "Feb" => 28, "Mar" => 31, "Apr" => 30, "May" => 31, "Jun" => 30, "Jul" => 31, "Aug" => 31, "Sept" => 30, "Oct" => 31, "Nov" => 30, "Dec" => 31);
   $curr_time = time();
   $time_ago = $curr_time - $timestamp;
   if($time_ago < 60) // seconds
   {
      $ext = $time_ago . " seconds ago..";
   }
   else
   {
      if($time_ago >= 60) // minutes
      {
         $time = floor($time_ago / 60);
         $seconds_remainder = $time_ago % 60;
         $ext = $time . " minutes " . $seconds_remainder . " seconds ago..";
         
         if($time >= 60) // hours
         {
            $hours = floor($time / 60);
            $minutes = $time % 60;
            $ext = $hours . " hours " . $minutes . " minutes ago..";
            if($hours >= 24) // days
            {
               $days = floor($hours / 24);
               $day_hours = $hours % 24;
               $ext = $days . " days " . $day_hours . " hours ago ..";
            }
         }
      }
   }
   return $ext;
}

 

Is there a cleaner approach to this?

Is there a cleaner approach to this?

 

If you're using PHP 5.3:

 

$timestamp = new DateTime('05:00');
$diff = $timestamp->diff(new DateTime());

echo $diff->format('%h hours, %i minutes');

 

See:

http://php.net/datetime.diff

http://php.net/dateinterval.format

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.