how to calculate time spent on my app by timestamp

2019-08-14 13:23发布

问题:

i have one column timestamp when user enters the app and another column when user leaves the app . i want to calculate the time spent on the app : sum(timestamp_exit) - sum (timestamp_enter) .

right now i've tried to right the current query :

select (SUM(unix_timestamp(`created_time_enter`))) as enter , (SUM(unix_timestamp(`created_time_exit`))) as exit
FROM `my_table` 

but i get large numbers and i don't know if it's the correct way. any suggestion?

回答1:

You could calculate this using the timeDiff function:

times = array();

foreach ($result as $row){
    // convert to unix timestamps
    $firstTime=strtotime($firstTime);
    $lastTime=strtotime($lastTime);

    // perform subtraction to get the difference (in seconds) between times
    $timeDiff=$lastTime-$firstTime;
    $times[] = $timeDiff;
    echo(secondsToTime($timeDiff));
    # 18 days, 23 hours, 41 minutes and 7 seconds
}

echo(secondsToTime(array_sum($times)));
#total of all times