2010-05-22 26 views
0

任何建議,使其更好?我的PHP函數如何將日期轉換爲Facebook時間戳? PHP新手

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); 
    } 
} 

}

+0

我的答案或其他答案是否爲您解決了這個問題?如果是這樣,請標記最正確的一個,因此此問題可以標記爲已回答。 – 2010-06-09 02:14:25

回答

0

它看起來還不錯,但是,如果你正在尋找的想法,以便能夠改善/改寫它,我採取了你的工作,稍微適應它,如下:

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); 
} 

由你決定是否要構建這個,或保留現有的代碼,或不保留什麼。

+0

噢,if((time() - $ d_u)== 3600)'可能會改變爲if((time() - $ d_u)<3900)'或類似的,以允許一點在你認爲「1小時前」的寬容中。例如,3900允許任何1:05的時間被認爲是1小時。 – 2010-05-22 02:30:35