php实现Facebook风格的 time ago函数
非常好用,只要把里面的英文替换成中文就行了
英文函数代码如下:
1 <?php 2 function nicetime($date) 3 { 4 if(empty($date)) { 5 return "No date provided"; 6 } 7 8 $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade"); 9 $lengths = array("60","60","24","7","4.35","12","10"); 10 11 $now = time(); 12 $unix_date = strtotime($date); 13 14 // check validity of date 15 if(empty($unix_date)) { 16 return "Bad date"; 17 } 18 19 // is it future date or past date 20 if($now > $unix_date) { 21 $difference = $now - $unix_date; 22 $tense = "ago"; 23 24 } else { 25 $difference = $unix_date - $now; 26 $tense = "from now"; 27 } 28 29 for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 30 $difference /= $lengths[$j]; 31 } 32 33 $difference = round($difference); 34 35 if($difference != 1) { 36 $periods[$j].= "s"; 37 } 38 39 return "$difference $periods[$j] {$tense}"; 40 } 41 42 $date = "2009-03-04 17:45"; 43 $result = nicetime($date); // 2 days ago 44 45 ?>
中文函数代码如下:
1 function nicetime($date) 2 { 3 if(empty($date)) { 4 return "No date provided"; 5 } 6 7 $periods = array("秒", "分钟", "小时", "天", "周", "月", "年", "十年"); 8 $lengths = array("60","60","24","7","4.35","12","10"); 9 10 $now = time(); 11 $unix_date = strtotime($date); 12 13 // check validity of date 14 if(empty($unix_date)) { 15 return "Bad date"; 16 } 17 18 // is it future date or past date 19 if($now > $unix_date) { 20 $difference = $now - $unix_date; 21 $tense = "以前"; 22 23 } else { 24 $difference = $unix_date - $now; 25 $tense = "from now"; 26 } 27 28 for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 29 $difference /= $lengths[$j]; 30 } 31 32 $difference = round($difference); 33 34 if($difference != 1) { 35 $periods[$j].= ""; 36 } 37 38 return "$difference$periods[$j]{$tense}"; 39 } 40 //用法示例 41 // $date = "2009-03-04 17:45"; 42 // $result = nicetime($date); // 2 days ago