PHP: date "Yesterday", "Today"

You have to compare day with day, secondes comparaison are totally wrong :

If we are today morning, that means yesterday night is today (by minus 24h) ^^

Here a method I use for Kinoulink ( a french startup ) :

public function formatDateAgo($value)
{
    $time = strtotime($value);
    $d = new \DateTime($value);

    $weekDays = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
    $months = ['Janvier', 'Février', 'Mars', 'Avril',' Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];

    if ($time > strtotime('-2 minutes'))
    {
        return 'Il y a quelques secondes';
    }
    elseif ($time > strtotime('-30 minutes'))
    {
        return 'Il y a ' . floor((strtotime('now') - $time)/60) . ' min';
    }
    elseif ($time > strtotime('today'))
    {
        return $d->format('G:i');
    }
    elseif ($time > strtotime('yesterday'))
    {
        return 'Hier, ' . $d->format('G:i');
    }
    elseif ($time > strtotime('this week'))
    {
        return $weekDays[$d->format('N') - 1] . ', ' . $d->format('G:i');
    }
    else
    {
        return $d->format('j') . ' ' . $months[$d->format('n') - 1] . ', ' . $d->format('G:i');
    }
}

function get_day_name($timestamp) {

    $date = date('d/m/Y', $timestamp);

    if($date == date('d/m/Y')) {
      $date = 'Today';
    } 
    else if($date == date('d/m/Y',now() - (24 * 60 * 60))) {
      $date = 'Yesterday';
    }
    return $date;
}
print date('G:i:s', $last_access).' '.get_day_name($last_access);

I would find the timestap for last midnight and the one before it, if $last_access is between the two timestamps, then display yesterday, anything greater than last midnight's timestamp would be today...

I believe that would be the quicker than doing date arithmetic.

Actually, I just tested this code and it seems to work great:

<?php
    if ($last_access >= strtotime("today"))
        echo "Today";
    else if ($last_access >= strtotime("yesterday"))
        echo "Yesterday";
?>

Tags:

Datetime

Php