You are here: Re: Help me fix my "x minutes ago" time script please :) « PHP Programming Language « IT news, forums, messages
Re: Help me fix my "x minutes ago" time script please :)

Posted by Rami Elomaa on 04/17/07 18:37

JamesG kirjoitti:
> I'm trying to convert a unix timestamp to a readable time, such as 4
> hours ago, or 25 minutes ago.
> My code is below:
>
> function ago($ts) {
> /* time difference */
> $ts = (time() - $ts);
>
> if($ts < 60) {
> /* <1 minute */
> return $ts . " seconds ago";
> } elseif($ts < 60 * 60) {
> /* <1 hour */
> return floor($ts / 60) . " minutes ago";
> } elseif ($ts < 60 * 60 * 2) {
> /* <2 hour */
> return "1 hour ago";
> } elseif ($ts < 60 * 60 * 24) {
> /* <24 hours = 1 day */
> return floor($ts / 60 * 60) . " hours ago";

Parenthesis missing here. First you divide by 60, then multiply by 60,
resulting in the same number you started with. This is the same as $ts *
60 / 60 which is the same as $ts. You're getting seconds instead of
hours. Put some parenthesis there to help php understund what you mean:
$ts / (60 * 60) // now it's executed in the correct order

> } elseif ($ts < 60 * 60 * 24 * 2) {
> /* <2 days */
> return "1 day ago";
> } elseif ($ts < 60 * 60 * 24 * 7) {
> /* <7 days = 1 week */
> return floor($ts / 60 * 60 * 24) . " days ago";

Same here: (60 * 60 * 24)

> } elseif ($ts < 60 * 60 * 24 * 30.5) {
> /* <30.5 days ~ 1 month */
> return floor($ts / 60 * 60 * 24 * 7) . " weeks ago";

and here: (60 * 60 * 24 * 7)

> } elseif ($ts < 60 * 60 * 24 * 365) {
> /* <365 days = 1 year */
> return floor($ts / 60 * 60 * 24 * 30.5) . " months ago";

and here

> } else {
> /* more than 1 year */
> return floor($ts / 60 * 60 * 24 * 365) . " years ago";

.... and also here: (60 * 60 * 24 * 365)

> }
> }
>
> Everything seems to work okay, except the "hours ago" case. A time 2
> hours ago will output "9692 hours ago", or a time 18 hours ago will
> read "9692 hours ago"!

If it seemd to work okay then perhaps you hadn't tested the last ones,
cos they seem to suffer from the same problem as the "x hours" case.

A personal sidenote: I *hate* "elseif", it's so ASP/VB/M$! The one and
only correct syntax is "else if" with a space between, if you ask me! :D
(Sure, elseif *is* valid code but it's just disgusting!)

--
Rami.Elomaa@gmail.com

"Wikipedia on vähän niinq internetin raamattu, kukaan ei pohjimmiltaan
usko siihen ja kukaan ei tiedä mikä pitää paikkansa." -- z00ze

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация