unix_timestamp日期和时间差

时间:2013-05-28 08:26:42

标签: php mysql date

我已将三个基本时间戳和时间存储到我的数据库表中,格式如下:

mysql> select receivedtime, requesttime, sla from table;
+---------------------+---------------------+----------+
| receivedtime        | requesttime         | sla      |
+---------------------+---------------------+----------+
| 2013-05-26 22:37:04 | 2013-05-26 12:37:04 | 02:59:59 |
| 2013-05-26 14:36:44 | 2013-05-21 12:39:09 | 72:00:00 |
+---------------------+---------------------+----------+
2 rows in set (0.00 sec)

我需要提出以下几个条件:

difference = (receivedtime - requesttime);

if [difference <= sla] 
{
   show meet
} else {
   show don't meet
}

说明:

receivedtime [timestamp] as because days 
requesttime [timestamp] as because days 
sla [time] as because hour

我检查了UNIX_TIMESTAMP() mysql, strtotime() php以及其他一些尝试。

我也检查了几个线程@ stackoverflow.com,但我找不到合适的解决方案。

任何想法......!

6 个答案:

答案 0 :(得分:2)

检查TIMESTAMPDIFF()SEC_TO_TIME()功能:

SELECT
    `receivedtime`,
    `requesttime`,
    `sla`,
    (SEC_TO_TIME(TIMESTAMPDIFF(SECOND, `requesttime`, `receivedtime`)) < `sla`) as `meet`
FROM
    `table`;

答案 1 :(得分:1)

尝试

SELECT receivedtime, 
       requesttime,
       CASE WHEN TIMESTAMPDIFF(SECOND, requesttime, receivedtime) < TIME_TO_SEC(sla) 
            THEN 'meet' ELSE 'don\'t meet' END sla
  FROM table1

这是 SQLFiddle 演示

答案 2 :(得分:1)

尝试从您的数据库中选择...

select TIMESTAMPDIFF(SECOND, receivedtime, requesttime) as difference, TIME_TO_SEC(sla) as slasecs from table

然后你可以做你的。

if [difference <= sla]
{
   show meet
} 
else 
{
   show don't meet
}

答案 3 :(得分:0)

这是一个日期时间字段,而不是时间戳字段。您应该首先阅读时间戳是什么。

你可以通过转换为时间戳然后减去来找出差异。

$recieved = strtotime($res['receivedtime']);
$requested = strtotime($res['requesttime']);
$difference = $recieved - $requested;
if($difference <= $sla){
  //do stuff
}

答案 4 :(得分:0)

你可以在SQL

中做到这一点
SELECT (UNIX_TIMESTAMP(receivedtime) - UNIX_TIMESTAMP(requesttime)) AS difference FROM table

它为您提供了几秒钟的差异。

答案 5 :(得分:0)

试试这个

select TIMESTAMPDIFF(SECOND,`requesttime`,`receivedtime`) as timeDiff FROM `table` 
WHERE TIMESTAMPDIFF(SECOND,`requesttime`,`receivedtime`) > TIME_TO_SEC(`sla`)

SEE SQL FIDDLE

您可以在mysql documentation

中找到相关内容