Unix timestamp to days, hours, minutes

前端 未结 4 888
南方客
南方客 2021-01-07 06:22

So, I have a field in my users table named last_active which updates every time a user reloads a page.
It\'s stored in unix timestamp.

I would like

4条回答
  •  渐次进展
    2021-01-07 06:57

    After finding dozens of broken or half-there solutions, I built the following function for UNIX timestamps.
    You can limit the detail level ...

    echo timeDiff(1350297908); will show "5 minutes, 42 seconds ago".
    echo timeDiff(1350297908, 1); will just show "5 minutes ago".

    function timeDiff( $from, $levels=7 ){  
        $now = time();
        $diff = ($from > $now) ? $from - $now : $now - $from;
        $status = ($from > $now) ? ' away' : ' ago';
        $times = array(31536000, 2628000, 604800, 86400, 3600, 60, 1);
        $words = array('year', 'month', 'week', 'day', 'hour', 'minute', 'second');
        $str = array();
        foreach ($times as $k=>$v){
            $val = floor($diff/$v);
            if ($val) {
                $str[] = $val .' '. $words[$k] . ($val==1 ? '' : 's');
                $levels--;
            }
            $diff %= $v;
            if ($levels==0) break;
        }
        return implode(', ', $str) . $status;
    }
    

提交回复
热议问题