php function to find Relative time in year, month, week, day etc

function to find time passed or time left between two time.from & to are two arguments.

to is optional and defaults to current time stamp if not given

1
echo time_relative("May 3, 1985 4:20 PM");

convert time to maonth days weeks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function time_relative($from, $to = null)
{
 $to = (($to === null) ? (time()) : ($to));
 $to = ((is_int($to)) ? ($to) : (strtotime($to)));
 $from = ((is_int($from)) ? ($from) : (strtotime($from)));
 $output = '';
 
 $units = array
 (
  "year"   => 29030400, // seconds in a year   (12 months)
  "month"  => 2419200,  // seconds in a month  (4 weeks)
  "week"   => 604800,   // seconds in a week   (7 days)
  "day"    => 86400,    // seconds in a day    (24 hours)
  "hour"   => 3600,     // seconds in an hour  (60 minutes) 
  "minute" => 60,       // seconds in a minute (60 seconds)
  "second" => 1         // 1 second
 );
 
 $diff = abs($from - $to);
 $suffix = (($from > $to) ? ("left") : ("old"));
 
 foreach($units as $unit => $mult)
  if($diff >= $mult)
  {
   $and = (($mult != 1) ? ("") : ("and "));
   $output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
   $diff -= intval($diff / $mult) * $mult;
  }
 $output .= " ".$suffix;
 $output = substr($output, strlen(", "));
 
 return $output;
}

No comments:

Post a Comment