Generate a twitter like timespan from a given timestamp in Symfony2 or ZF2

We must have seen the human readable time in twitter saying that something like about 2 hours ago… etc. In this post we will see a walk around on how to do it in a Symfony2, Zend Framework2 or any other PHP based application. I wrote and used this class as helper in one of my Symfony2 project. This helper could be used in Zend Framework as well.

I used some PHP magic methods to cope with different configuration settings so that any one can modify the setting in runtime. I tried to keep it very much extendable. Let’s have a look on the class:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
 
// the following line is used in Symfony2, you may use it if your project is Symfony2
//namespace ApplicationNpndBundleHelper;
 
/**
 * TimespanHelper.
 *
 * generate a twitter like timespan from a give timestamp
 *
 * @package    Npnd
 * @subpackage Helper
 * @author     Nurul Ferdous <nurul.ferdous@gmail.com>
 */
class TimespanHelper
{
 
    /**
     * @var integer $timstamp
     */
    private $_formattedString;
    /**
     * @var object $_config
     */
    protected $_config;
 
    /**
     * Constructor.
     *
     * return the formatted timstamp from given array
     *
     * @param Array $config
     * @return string formatted timstamp with ago [like twitter]
     */
    public function __construct(Array $config = null)
    {
        $this->_init();
 
        if (count($config) && is_array($config)) {
            $this->_config = (object) array_merge((array) $this->_config, $config);
        }
 
        return $this->getTimeSince();
    }
 
    /**
     * initializing default configuration
     * 
     */
    private function _init()
    {
        $this->_config = new stdClass();
        $this->_config->from = 1;
        $this->_config->to = time();
        $this->_config->buffer = '259200';
        $this->_config->lang_year = 'Year';
        $this->_config->lang_month = 'Month';
        $this->_config->lang_week = 'Week';
        $this->_config->lang_day = 'Day';
        $this->_config->lang_hour = 'Hour';
        $this->_config->lang_minute = 'Minute';
        $this->_config->lang_second = 'Second';
        $this->_config->lang_ago = 'ago';
        $this->_config->moment_ago = 'a moment ago';
        $this->_formattedString = $this->_config->moment_ago;
    }
 
    /**
     * property getter magic function
     *
     * @param string> $prop
     * @return string
     */
    public function __get($prop)
    {
        return $this->$prop;
    }
 
    /**
     * property setter magic function
     *
     * @param string> $prop
     * @return string
     */
    public function __set($prop, $val)
    {
        $this->$prop = $val;
    }
 
    /**
     * render the returned string to browser
     * 
     * @return string returned value
     */
    public function __toString()
    {
        return $this->_formattedString;
    }
 
    /**
     * get twitter like timstampspan
     *
     * @param integer $time timestamp
     * @param array $config
     * @return string formatted timstamp with ago [like twitter]
     */
    public function getTimeSince($time = false, $config = array())
    {
        if (count($config) && is_array($config)) {
            $this->_config = (object) array_merge((array) $this->_config, $config);
        }
 
        if ($this->_config->to <= $this->_config->from) {
            $this->_config->from = 1;
        } else {
            $this->_config->from = $this->_config->to - $this->_config->from;
        }
 
        if ($this->_config->from > $this->_config->to) {
            return date('M jS, Y', $this->_config->from);
        }
 
        $str = '';
        $years = floor($this->_config->from / 31536000);
 
        if ($years > 0) {
            $str .= $years . ' ' . (($years > 1) ? $this->_config->lang_year . 's' : $this->_config->lang_year) . ', ';
        }
 
        $this->_config->from -= $years * 31536000;
        $months = floor($this->_config->from / 2628000);
 
        if ($years > 0 OR $months > 0) {
            if ($months > 0) {
                $str .= $months . ' ' . (($months > 1) ? $this->_config->lang_month . 's' : $this->_config->lang_month) . ', ';
            }
 
            $this->_config->from -= $months * 2628000;
        }
 
        $weeks = floor($this->_config->from / 604800);
 
        if ($years > 0 OR $months > 0 OR $weeks > 0) {
            if ($weeks > 0) {
                $str .= $weeks . ' ' . (($weeks > 1) ? $this->_config->lang_week . 's' : $this->_config->lang_week) . ', ';
            }
 
            $this->_config->from -= $weeks * 604800;
        }
 
        $days = floor($this->_config->from / 86400);
 
        if ($months > 0 OR $weeks > 0 OR $days > 0) {
            if ($days > 0) {
                $str .= $days . ' ' . (($days > 1) ? $this->_config->lang_day . 's' : $this->_config->lang_day) . ', ';
            }
 
            $this->_config->from -= $days * 86400;
        }
 
        $hours = floor($this->_config->from / 3600);
 
        if ($days > 0 OR $hours > 0) {
            if ($hours > 0) {
                $str .= $hours . ' ' . (($hours > 1) ? $this->_config->lang_hour . 's' : $this->_config->lang_hour) . ', ';
            }
 
            $this->_config->from -= $hours * 3600;
        }
 
        $minutes = floor($this->_config->from / 60);
 
        if ($days > 0 OR $hours > 0 OR $minutes > 0) {
            if ($minutes > 0) {
                $str .= $minutes . ' ' . (($minutes > 1) ? $this->_config->lang_minute . 's' : $this->_config->lang_minute) . ', ';
            }
 
            $this->_config->from -= $minutes * 60;
        }
 
        if ($str == '') {
            $str .= $this->_config->from . ' ' . (($this->_config->from > 1) ? $this->_config->lang_second . 's' : $this->_config->lang_second) . ', ';
        }
        $this->_formattedString = substr(trim($str), 0, -1) . ' ' . $this->_config->lang_ago;
        return $this->_formattedString;
    }
 
    /**
     * calculate and return human readable time
     *
     * @param array $config $config['from'] and $config['to']
     * @return string date difference
     */
    public function dateDiff(Array $config)
    {
        $config['lang_ago'] = '';
        $this->_config = (object) array_merge((array) $this->_config, $config);
        return $this->getTimeSince();
    }
 
    /**
     * Returns the canonical name of this helper.
     *
     * @return string The canonical name
     */
    public function getName()
    {
        return 'timespan';
    }
 
}

and here is some example usage of this helper:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
require_once 'TimespanHelper.php';
/**
 * example-1
 */
echo new TimespanHelper(array('from' => time() - 18600));
 
/**
 * example-2
 */
echo new TimespanHelper(array('from' => 317144200, 'to' => strtotime('Jan 20th, 2000')));
 
 
/**
 * example-2
 */
$time = new TimespanHelper();
echo $time->dateDiff(array('from' => 317144200, 'to' => strtotime('Jan 20th, 2000')));
 
?>
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Identi.ca
  • Posterous
  • Technorati
  • Tumblr
  • Twitter
  • HackerNews
  • LinkedIn
  • Live
  • Netvibes
  • Reddit
  • StumbleUpon
  • Yahoo! Bookmarks
  • Yahoo! Buzz

No related posts.

4 Responses to “Generate a twitter like timespan from a given timestamp in Symfony2 or ZF2”

  1. Wow sir that’s cool. Can I use it as codeIgniter helper or not?

  2. Ferdous Bhai thanks for your nice article.

  3. Your __get and __set don’t add any functionality to the class. All that those methods will do as you’ve implemented them is allow outside classes to access and change private and protected variables within the class. With those methods in place you’ve made everything public. I’d suggest removing them.

Trackbacks/Pingbacks

  1. Tweets that mention Generate a twitter like timespan from a give timestamp in Symfony2 or ZF2 | Dynamic Guy -- Topsy.com - [...] This post was mentioned on Twitter by Nurul Ferdous, Nurul Ferdous. Nurul Ferdous said: wrote a blog post on ...

Leave a Reply