【问题标题】:php relative time problemsphp相对时间问题
【发布时间】:2011-06-10 02:56:10
【问题描述】:

我有这个函数可以计算出从某个日期以来经过的相对时间,

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

我正在向函数传递一个日期为“2011-01-16 12:30”,但是我返回的日期错误,这意味着 $unix_date 是空的,但是如果我在函数中死了,我会得到 $date它被传递给函数,但是它在它之前返回一个 (,下面是我调用该方法的方式。

echo nicetime(date('Y:m:d G:i', $a['created_at']))

【问题讨论】:

  • 你说的“如果我死了怎么办”是什么意思
  • 进行了编辑以使其更清晰,基本上,如果我在方法中运行 die 语句,它将返回日期并进行处理(
  • $a['created_at'] 是时间戳吗?如果它是一个字符串,那么 date 将返回一个 1969 年的日期。Epoch fail
  • 另外,您使用的是哪个版本的 PHP?如果您使用的是 5.1.0 之前的版本,则 strToTime() 将在出错时返回 -1 而不是 bool(false)
  • $a['created_at'] 是一个 unix 时间戳

标签: php datetime codeigniter time


【解决方案1】:
echo nicetime("2011-01-16 12:30");

对我来说很好。我建议你确保

 $a['created_at']

正在给你你的东西。可以试试

$dtDate = $a['created_at'];
$strDate = date('Y:m:d G:i', $dtDate );
echo $strDate;
echo nicetime($strDate);

确保 $strDate 是您认为的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多