timeDiffInWords - a function to keep handy
Posted by Felix Geisendörfer, on Apr 29, 2006 - in PHP & CakePHP » Views & Helpers
Deprecated post
The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.
Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.
Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).
Today I've been looking in my old projects for a function like this for about 20 minutes until I decided to code it again. The problem is, sometimes you need a php functions to convert a time difference (in seconds) into words. Since I think it's a function that could be useful to other folks as well, and I need a place to store it, I'll put it in here:
-
function __timeDiffInWords($time)
-
{
-
$days = ($time / (1 * 60 * 60 * 24));
-
$time = $time % (1 * 60 * 60 * 24);
-
$hours = ($time / (1 * 60 * 60));
-
$time = $time % (1 * 60 * 60);
-
$minutes = ($time / (1 * 60));
-
$time = $time % (1 * 60);
-
$seconds = $time;
-
-
-
if ($days==1)
-
else if ($days > 1)
-
-
if ($hours==1)
-
else if ($hours > 1)
-
-
if ($minutes==1)
-
else if ($minutes > 1)
-
-
if ($seconds==1)
-
else if ($seconds > 1)
-
-
-
}
4 Comments
The difference is that TimeHelper::timeAgoInWords() expects to be provided with a datetime in the past or present and tells you the difference between it and the time() now. The time values I deal with are only time Differences in seconds and not absolute unix timestamps. In the moment I was looking at the TimeHelper in search of a function like this I thought about using timeAgoInWords() but since it didn't work as expected right away I dropped the idea of using it. Now that you point it out to me again I realize that I can use something like this as well:
$time->timeAgoInWords(time()+$ptime, 'j/n/y', true);
But the other issue would be that it only works with english. The version of __timeDiffInWords I wrote was in German and I just changed the strings to English for the blog.
There's a time helper available in more than one language on cakeforge, which *may* address the need for a single (but not English) language time helper. Alternatively, if /app/views/helpers/time.php is (user)defined, you can override the functions, if only to change the language, without tampering with the version shipped with the core.
Alright, I stay corrected on this one ; ). At least the function can be considered useful when dealing with non cakephp projects. And I also got a JavaScript version of it which is almost the same, just a little different in the syntax.


What's the difference to TimeHelper::timeAgoInWords()?