|
Posted by JamesG on 04/17/07 18:56
On Apr 17, 7:37 pm, Rami Elomaa <rami.elo...@gmail.com> wrote:
> 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.Elo...@gmail.com
>
> "Wikipedia on vähän niinq internetin raamattu, kukaan ei pohjimmiltaan
> usko siihen ja kukaan ei tiedä mikä pitää paikkansa." -- z00ze
Thanks so much for correcting the silly mistake.
I also hate nested elseifs but in this case it's the only way to do it
I think-- I considered a switch statement but that isn't useful in
this instance.
Navigation:
[Reply to this message]
|