PHP中的时间差异

时间:2013-05-31 23:29:23

标签: php sql

我在数据库中有一个包含以下内容的临时表:

 userid | time              
--------|---------------------
 1      | 13-01-24 00:04:01 
 1      | 13-01-24 00:04:04 
 1      | 13-01-24 00:05:06 
 2      | 13-01-24 00:06:06 
 2      | 13-01-24 00:06:08 

我想得到如下答案:

1,  0 second
1,  3 second
1,  62 second
2,  60 second
2,  2 second

我尝试了'TIMEDIFF'脚本(max(time)min(time)),但它没有输出我想要的内容。请帮助,我正在使用PHP。

2 个答案:

答案 0 :(得分:1)

MySQL解决方案:

SET @prev_time = null;
SELECT userid, IFNULL(timediff(`time`,@prev_time), 0) diff,
       @prev_time := `time`
FROM mytable
ORDER BY time

SQLFIDDLE

答案 1 :(得分:0)

PHP解决方案:

(同样是@Barmar的解决方案,但在php中)

<?php
$timearray = array("13-01-24 00:04:01", "13-01-24 00:04:04", "13-01-24 00:05:06", "13-01-24 00:06:06", "13-01-24 00:06:08");
$prevtimestamp = null;
foreach($timearray as $it) {
    $datetime = explode(" ", $it);
    $date = explode("-", $datetime[0]);
    $time = explode(":", $datetime[1]);
    $newtimestamp = mktime($time[0], $time[1], $time[2], $date[1], $date[0], $date[2]);
    if($prevtimestamp == null) $prevtimestamp = $newtimestamp;
    echo $newtimestamp - $prevtimestamp . " seconds";
    $prevtimestamp = $newtimestamp;
}
?>