PHP:相对日期和清洁“昨天”& “前天”

时间:2015-11-10 17:48:13

标签: php date relative relative-date

我修改了一个脚本来获取时间戳(x次前)的相对日期,我想调整它以增加另一个级别的精度,如“昨天”或“前天”。

尝试了这个并且它有效,但它不是很干净,您是否知道如何在“最近几天”之后简化这两行?

function relativedate($timestamp, $limit = 1209600){
    $diff = time() - $timestamp;
    $time = ($diff < 1) ? 1 : $diff;
    $times = array(
        "year"   => 31536000,
        "month"  => 2592000,
        "week"   => 604800,
        "day"    => 86400,
        "hour"   => 3600,
        "minute" => 60,
        "second" => 1
    );

    // Date limit as displayed full
    if ($limit > 0 && $diff > $limit){
        return "on ".date("d/m/Y - H:i:s", $timestamp);
    }

    // Recent days
    if ($diff > $times["day"]       && $diff < ($times["day"] * 2)-1) return "yesterday";
    if ($diff > ($times["day"] * 2) && $diff < ($times["day"] * 3)-1) return "the day before yesterday";

    // Display x time ago
    foreach ($times as $unit => $seconds){
        if ($time < $seconds) continue;
        $amount = floor($time / $seconds);
        return "since $amount $unit".(($amount > 1) ? "s" : "");
    }
}

修改
我的编辑和回复都有效,但它仍然不是那么干净?试图弄清楚我怎么能以另一种方式做到这一点......欢迎任何提议:) 关于strtotime("yesterday")strtotime("-2 days")

1 个答案:

答案 0 :(得分:1)

试试这个:

function relativedate($timestamp, $limit = 1209600){
    $diff = time() - $timestamp;
    $time = ($diff < 1) ? 1 : $diff;
    $value = '';
    $times = array(
        31536000 => "year",
        2592000 => "month",
        604800 => "week",
        86400 => "day",
        3600 => "hour",
        60 => "minute",
        1 => "second"
    );
    // Date limit as displayed full
    if ($limit > 0 && $diff > $limit){
        return "on ".date("d/m/Y - H:i:s", $timestamp);
    }
    // Recent days
    if ($diff >= (24*60*60) && $diff < (48*60*60)) {
        $value = "yesterday";
    }
    if ($diff >= (48*60*60) && $diff < (72*60*60)) {
        $value = "the day before yesterday";
    }
    // Display x time ago
    foreach ($times as $seconds => $text){
        if ($time < $seconds) continue;
        $amount = floor($time / $seconds);
        $value = "since $amount $text".(($amount > 1 && $text != "mois") ? "s" : "");
        break;
    }
    return $value;
}

echo relativedate(strtotime("-1 hour")).'<br />';
echo relativedate(strtotime("-23 hour")).'<br />';
echo relativedate(strtotime("-25 hour")).'<br />';
echo relativedate(strtotime("-49 hour")).'<br />';
echo relativedate(strtotime("-73 hour")).'<br />';
echo relativedate(strtotime("-1173 hour")).'<br />';

结果:

since 1 hour
since 23 hours
since 1 day
since 2 days
since 3 days
on 22/09/2015 - 21:47:59