Displaying the elapsed time

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 107

Displaying the elapsed time

Hi
Does anyone has a php code to display the elapsed time?
Like: one hour ago, 1 day and 3 hours ago, ...
Thank you.

Admin Posts: 805
Hi
You can use the timeElapsed() function, from this example:

Code: Select all

function timeElapsed($t1, $t2 = null) {
/*
 Returns an object with time elapsed from $t1 to $t2. Code From: https://coursesweb.net/php-mysql/
 Properties: y = years, m = months, w = weeks, d = days (till end of month), d2 = days till end of week, h = hours, i = minutes, s = seconds, days = total days
 $t2 is Optional, if not passed, will be set the curent date-time
 $t2 must be higher than $t1, they can be in Unix Timestamp, or string with a valid literaly date/time format (day.month.year , or: year-month-day, or: Year-Month-Day Hour:Minute:Seconds)
*/
  $t1 = is_int($t1) ? new DateTime('@'. $t1) : new DateTime($t1);
  $t2 = ($t2 == null) ? new DateTime() : (is_int($t2) ? new DateTime('@'. $t2) : new DateTime($t2));

  // object with the difference from $t1 to $t2
  $df = $t2->diff($t1);
  $df->w = floor($df->days / 7) - ($df->y * 52) - $df->m * 4;   // weeks
  $df->d2 = $df->d - ($df->w * 7);    // days till the end of week
  return $df;

// $df->y = years, $df->m = months, $df->w = weeks, $df->d = days (till end of month), $df->d2 = days till end of week, $df->h = hours, $df->i = minutes, $df->s = seconds
}

// Example
$time = 1402008961;     // Timestamp
$t_diff = timeElapsed($time);    // gets the object with time difference

// Output (if show elapsed weeks ($w property), use $d2 property for remaining days till end of week)
echo sprintf('%d month, %d weeks, %d days, and %d hours ago', $t_diff->m, $t_diff->w, $t_diff->d2, $t_diff->h);
echo '<br>Total days: '. $t_diff->days .' days ago.';  
Result:

Code: Select all

1 month, 2 weeks, 3 days, and 11 hours ago
Total days: 47 days ago.