1

php.net 文档中有一个非常好的函数,它使您能够以 Facebook 样式的方式(例如,、、2 minutes ago4 weeks ago)格式化时间3 years ago

但是,我更喜欢 Stackoverflow 和 Apple Mail 的方式,通常如下:

  1. 当前日期在x seconds agox hours ago或时间中列出(例如,4:35pm)。
  2. 昨天被列为“昨天”。
  3. 之后的所有日子都按月/日/年列出。

有没有人改编这个 php.net 脚本来做到这一点,或者可能共享一个不同的脚本来实现相同的目标?

<?php 

  function nicetime($date)
 {
    if(empty($date)) {
      return "No date provided";
    }

$periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths         = array("60","60","24","7","4.35","12","10");

$now             = time();
$unix_date         = strtotime($date);

   // check validity of date
if(empty($unix_date)) {    
    return "Bad date";
}

// is it future date or past date
if($now > $unix_date) {    
    $difference     = $now - $unix_date;
    $tense         = "ago";

} else {
    $difference     = $unix_date - $now;
    $tense         = "from now";
}

for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
    $difference /= $lengths[$j];
}

$difference = round($difference);

if($difference != 1) {
    $periods[$j].= "s";
}

  return "$difference $periods[$j] {$tense}";
}

$date = "2009-03-04 17:45";
$result = nicetime($date); // 2 days ago

?>
4

1 回答 1

1

好的,我回答了我自己的问题。

for关键是要跟踪循环经历了多少轮除法,直到当前时间减去输入时间的商$difference除以数组项的第 th 值小$j于此数组的第 th 值。$lengths$j+1

我通过在以下修改版本中增加变量$i(注意演示我上面提到的 3 点中的每一个的子句)来跟踪这一点:if/elseif/elsenicetime()

     ///http://php.net/manual/en/function.time.php
  function nicetime($date)
 {
    if(empty($date)) {
      return "No date provided";
    }

$periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths         = array("60","60","24","7","4.35","12","10");

$now             = time();
$unix_date         = strtotime($date);

   // check validity of date
if(empty($unix_date)) {    
    return "Bad date";
}

// is it future date or past date
if($now > $unix_date) {    
    $difference     = $now - $unix_date;
    $tense         = "ago";

} else {
    $difference     = $unix_date - $now;
    $tense         = "from now";
}
$i=0;
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
    $i++;
    $difference /= $lengths[$j];
}

$difference = round($difference);

if($difference != 1) {
    $periods[$j].= "s";
}

if($i<3){
    $day="$difference $periods[$j] {$tense}";
    return $day;
    //satisfies case #1 where time is listed as seconds, minutes, hours ago
}

elseif($i==3){
    $difference == 1 && $periods[$j]=='day' ? $day='yesterday':     
    $day="$difference $periods[$j] {$tense}";
    return $day;        
    //satisfies case #2 where time is listed as yesterday if not the current day

}
else{
    return $date;       
    // satisfies case #3 where date is listed as M/D/Y if greater than a week old
}   

}

echo "case#1: ".nicetime('2012-08-13 23:12:16');
echo "case#2: ".nicetime('2012-08-12 23:12:16');
echo "case#3: ".nicetime('2012-07-07 23:12:16');
于 2012-08-13T23:22:16.843 回答