Calculate the difference between date/times in PHP

前端 未结 5 1413
名媛妹妹
名媛妹妹 2020-12-11 19:17

I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.

I have tried a few things but the first just gave

5条回答
  •  盖世英雄少女心
    2020-12-11 19:31

    Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:

    function getTimeDifferenceToNowString($timeToCompare) {
    
            // get current time
            $currentTime = new Date();
            $currentTimeInSeconds = strtotime($currentTime);
            $timeToCompareInSeconds = strtotime($timeToCompare);
    
            // get delta between $time and $currentTime
            $delta = $currentTimeInSeconds - $timeToCompareInSeconds;
    
            // if delta is more than 7 days print the date
            if ($delta > 60 * 60 * 24 *7 ) {
                return $timeToCompare;
            }   
    
            // if delta is more than 24 hours print in days
            else if ($delta > 60 * 60 *24) {
                $days = $delta / (60*60 *24);
                return $days . " days ago";
            }
    
            // if delta is more than 60 minutes, print in hours
            else if ($delta > 60 * 60){
                $hours = $delta / (60*60);
                return $hours . " hours ago";
            }
    
            // if delta is more than 60 seconds print in minutes
            else if ($delta > 60) {
                $minutes = $delta / 60;
                return $minutes . " minutes ago";
            }
    
            // actually for now: if it is less or equal to 60 seconds, just say it is a minute
            return "one minute ago";
    
        }
    

提交回复
热议问题