Relative date and a cleaner "yesterday" & "the day before yesterday"

459 Views Asked by At

I modified a script to get a relative date from a timestamp (x times ago) and I would like to tweak it to add another level of precision like "yesterday" or "the day before yesterday".

Tried this and it works but it's not very clean, do you have an idea how can I simplify the two lines after "Recent days"?

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

Both my edit and the reply works but it's still not so clean? Trying to figure out how I can do it in another way.

Though about strtotime("yesterday") and strtotime("-2 days")?

1

There are 1 best solutions below

4
Kostas Mitsarakis On

Try this:

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 />';

Result:

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