Zend Framework Source Code Snippets

Relative time view helper

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
<?php
 
/**
 * Given a time, it gives you the time since then in a friendly format.
 * * @package
 * @category
 * @author      Dave Marshall
 * @author      $Author: $
 * @version     $Rev: $ * @since       $Date: $
 * @link        $URL: $
 */
class Zend_View_Helper_TimeSince
{    function timeSince($time, $from = null)
    {
        if ($from == null) {
            $from = time();
        }        $time = $from - $time;
 
        $chunks = array(
            array(60 * 60 * 24 * 365 , 'year'),
            array(60 * 60 * 24 * 30 , 'month'),            array(60 * 60 * 24 , 'day'),
            array(60 * 60 , 'hour'),
            array(60 , 'minute'),
            array(1 , 'second')
        ); 
        for ($i = 0, $j = count($chunks); $i < $j; $i++) {
            $seconds = $chunks[$i][0];
            $name = $chunks[$i][1];
            if (($count = floor($time / $seconds)) != 0) {                break;
            }
        }
 
        $print = ($count == 1) ? '1 '.$name : "$count {$name}s";        return $print;
    }
}
 
## Example Usage 
<span title="<?php echo date('r', $timestamp);?>"><?php echo $this->timeSince($timestamp);?></span>

Comments

neil_garb neil_garb
2 years ago

I've implemented this exact same function, and I think a nice addition (I haven't done this myself) would be to specify how many more granular chunks to show, so e.g.

$this->trimSince($timestamp) might give you '3 weeks'

but

$this->trimSince($timestamp, 1) might give you '3 weeks 2 days'

and

$this->trimSince($timestamp, 2) might give you '3 weeks 2 days 14 hours'

etc.

davedevelopment davedevelopment
2 years ago

Good call Neil.

Another variation would be how granular to start with, so maybe we could have 15 days 14 hours etc.

It could also round up or down and say About 4 hours ago etc.

bytte bytte
2 years ago

Great. This will come in handy.

Pacek Pacek
2 years ago

Very handy, thanx.

alessiofx alessiofx
2 years ago

I have a problem, how do I install this class?


Thanks

umpirsky umpirsky
2 years ago

@davedevelopment Why doesn't it extends Zend_View_Helper_Abstract?
Maybe we can merge one good snippet, check out http://zfsnippets.com/snippets/view/id/39 :)

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

Snippet description

This is a simple view helper I use to show the the dates and times on this site.

Snippet details

Created:
davedevelopment davedevelopment
2 years ago
Edited:
davedevelopment davedevelopment
2 years ago
Revision Id:
39
Edit Message:
Removed vcs tags
Tags:
view helper date time
Comments:
6
Views:
1701
Points:
0 (0 votes)

History

r39

Removed vcs tags

davedevelopment davedevelopment
2 years ago
diff
r1

Initial Release

davedevelopment davedevelopment
2 years ago