Zend Framework Source Code Snippets

Zend_View_Helper_Relativetime

Bookmark and Share
1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
<?php
 
class Zend_View_Helper_Relativetime 
{
  public function relativetime($unixtime, $accuracy = 2, $splitter = ', ')  {
    if (time() > $unixtime)
    {
      $unixtime = time() - $unixtime;
    }    else
    {
      $unixtime = $unixtime - time();
    }
     $mt = new Zend_Measure_Time($unixtime);
    $units = $mt->getConversionList();
 
    $tr = Zend_Registry::get('Zend_Translate');
     $chunks = array(
      Zend_Measure_Time::YEAR,
      Zend_Measure_Time::WEEK,
      Zend_Measure_Time::DAY,
      Zend_Measure_Time::HOUR,      Zend_Measure_Time::MINUTE,
      Zend_Measure_Time::SECOND
    );
 
    $translations = array(      'year' => array($tr->_('year'), $tr->_('years')),
      'week' => array($tr->_('week'), $tr->_('weeks')),
      'day' => array($tr->_('day'), $tr->_('days')),
      'h' => array($tr->_('hour'), $tr->_('hours')),
      'min' => array($tr->_('minute'), $tr->_('minutes')),      's' => array($tr->_('second'), $tr->_('seconds'))
    );
 
    $measure = array();
     for($i=0; $i < count($chunks); $i++)
    {
      $chunk_seconds = $units[$chunks[$i]][0];
 
      if ($unixtime >= $chunk_seconds)      {
        $measure[$units[$chunks[$i]][1]] = floor($unixtime / $chunk_seconds);
        $unixtime %= $chunk_seconds;
      }
    }    
    $measure = array_slice($measure, 0, $accuracy, true);
    
    $str = '';
    foreach($measure as $key => $val)    {
      $unit = $translations[$key];
 
      if($val == 1)
      {        $unit = $unit[0];
      }
      else
      {
        $unit = $unit[1];      }
 
      $str .= $val . ' ' . $unit . $splitter;
    }
     return substr($str, 0, 0 - strlen($splitter));
 
  }
}

Comments

You must login before commenting on a snippet. If you do not have an account, please register.

Snippet description

Yet another relative time view helper.

Snippet details

Created:
raspi raspi
2 years ago
Edited:
raspi raspi
2 years ago
Revision Id:
62
Edit Message:
Initial Release
Tags:
relative time since until date
Comments:
0
Views:
1497
Points:
1 (1 votes)

History

r62

Initial Release

raspi raspi
2 years ago