PHP: date “Yesterday”, “Today”

后端 未结 9 1815
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 10:20

I have a little function that shows latest activity, it grab timestamp in unix format from the db, and then it echo out with this line:

 date(\"G:i:s j M -Y\         


        
9条回答
  •  独厮守ぢ
    2020-12-09 11:03

    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');
        }
    }
    

提交回复
热议问题