Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Human Time Difference

It's often more appropriate to return a date difference in a human readable string. We've posted a version of WordPress' human_time_diff() function here (to be used outside of WP). However, there are countless means of achieving the same result. The following is a function we also regularly use.

The function accepts any strtotime() compatible time string.

1
<?php 
2
/*
3
 Human Time Difference
4
 http://www.beliefmedia.com/code/php-snippets/human-time-difference
5
 See also: http://www.beliefmedia.com/readable-time-difference
6
*/
7
 
8
function beliefmedia_time_difference($date) {
9
 
10
  /* If no date provided */
11
  if (empty($date)) return "No date provided";
12
 
13
  $periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade');
14
  $lengths = array('60', '60', '24', '7', '4.35', '12', '10');
15
 
16
  /* The two timestamps */
17
  $now = time(); $unix_date = strtotime($date);
18
 
19
  /* Check validity of date */
20
  if (empty($unix_date)) return "Bad date";
21
 
22
  /* Determine tense of date */
23
  if ($now > $unix_date) {
24
     $difference = $now - $unix_date;
25
     $tense = 'ago';
26
  } else {
27
     $difference = $unix_date - $now;
28
     $tense = 'from now';
29
  }
30
 
31
  for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
32
   $difference /= $lengths[$j];
33
  }
34
 
35
  $difference = round($difference);
36
  if ($difference != 1) $periods[$j] .= 's';
37
 
38
 return "$difference $periods[$j] {$tense}";
39
}
40
 
41
 
42
/* Usage */
43
$date = "2017-06-20 11:00am";
44
echo beliefmedia_time_difference($date);
45
?>

See also our WP snippet: Display Time To Published or Scheduled Posts.

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment