RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

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.

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment

window.addEventListener('scroll', bm_scroll_percent);