views:

43

answers:

1

any suggestions to make it better?

function convertToFBTimestamp($date){
$this_date = date('Y-m-d-H-i-s', strtotime($date));
$cur_date = date('Y-m-d-H-i-s');

list ($this_year, $this_month, $this_day, $this_hour, $this_min, $this_sec) = explode('-',$this_date);
list ($cur_year, $cur_month, $cur_day, $cur_hour, $cur_min, $cur_sec) = explode('-',$cur_date);

$this_unix_time = mktime($this_hour, $this_min, $this_sec, $this_month, $this_day, $this_year);
$cur_unix_time = mktime($cur_hour, $cur_min, $cur_sec, $cur_month, $cur_day, $cur_year);
$cur_unix_date = mktime(0, 0, 0, $cur_month, $cur_day, $cur_year);

$dif_in_sec = $cur_unix_time - $this_unix_time;
$dif_in_min = (int)($dif_in_sec / 60);
$dif_in_hours = (int)($dif_in_min / 60);

if(date('Y-m-d',strtotime($date))== date('Y-m-d'))
{
    if($dif_in_sec < 60)
    {
        return $dif_in_sec." seconds ago";
    }
    elseif($dif_in_sec < 120)
    {
        return "about a minute ago";
    }
    elseif($dif_in_min < 60)
    {
        return $dif_in_min." minutes ago";
    }
    else
    {
        if($dif_in_hours == 1)
        {
            return $dif_in_hours." hour ago";
        }
        else
        {   
            return $dif_in_hours." hours ago";
        }
    }
}
elseif($cur_unix_date - $this_unix_time < 86400 )
{
    return strftime("Yesterday at %l:%M%P",$this_unix_time);
}
elseif($cur_unix_date - $this_unix_time < 259200)
{
    return strftime("%A at %l:%M%P",$this_unix_time);
}
else 
{
    if($this_year == $cur_year)
    {
        return strftime("%B, %e at %l:%M%P",$this_unix_time);
    }
    else
    {
        return strftime("%B, %e %Y at %l:%M%P",$this_unix_time);
    }   
}

}

A: 

It looks pretty good, but, if you are looking for ideas to be able to improve/rewrite it, I have taken your work and slightly adapted it as below:

function convertToFBTimestamp( $d ) {
  $d = ( is_string( $d ) ? strtotime( $d ) : $d ); // Date in Unix Time

  if( ( time() - $d ) < 60 )
    return ( time() - $d ).' seconds ago';
  if( ( time() - $d ) < 120 )
    return 'about a minute ago';
  if( ( time() - $d ) < 3600 )
    return (int) ( ( time() - $d ) / 60 ).' minutes ago';
  if( ( time() - $d ) == 3600 )
    return '1 hour ago';
  if( date( 'Ymd' ) == date( 'Ymd' , $d ) )
    return (int) ( ( time() - $d ) / 3600 ).' hours ago';
  if( ( time() - $d ) < 86400 )
    return 'Yesterday at '.date( 'g:ia' , $d );
  if( ( time() - $d ) < 259200 )
    return date( 'l \a\t g:ia' , $d );
  if( date( 'Y' ) == date( 'Y' , $d ) )
    return date( 'F, jS \a\t g:ia' , $d );
  return date( 'j F Y \a\t g:ia' , $d );
}

Up to you whether you want to build off this, or keep your existing code, or what-not.

Lucanos
Oh, and the line `if( ( time() - $d_u ) == 3600 )` might be worth changing to `if( ( time() - $d_u ) < 3900 )` or similar, to allow for a bit of tolerance in what you consider "1 hour ago". 3900, for instance, allows anything up to 1:05 to be considered as 1hr.
Lucanos