user2160110
user2160110

Reputation:

unix_timestamp date and time difference

I have stored three essential timestamps and times into my database table, format as follows:

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)

I need to put a few conditions like below:

difference = (receivedtime - requesttime);

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

legend:

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

I have checked UNIX_TIMESTAMP() of mysql, strtotime() of php and few other tries.

I also have checked several threads @ stackoverflow.com, but I can't find proper solution.

Any ideas...!

Upvotes: 0

Views: 152

Answers (6)

james raygan
james raygan

Reputation: 701

Try selecting from your database like this ...

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

and then you can do your.

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

Upvotes: 1

alwaysLearn
alwaysLearn

Reputation: 6950

Try this

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

SEE SQL FIDDLE

You can find relevant in mysql documentation

Upvotes: 0

BlitZ
BlitZ

Reputation: 12168

Check TIMESTAMPDIFF() and SEC_TO_TIME() functions:

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

Upvotes: 2

peterm
peterm

Reputation: 92785

Try

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

Here is SQLFiddle demo

Upvotes: 1

kelunik
kelunik

Reputation: 6908

You can do that in SQL

SELECT (UNIX_TIMESTAMP(receivedtime) - UNIX_TIMESTAMP(requesttime)) AS difference FROM table

it gives you the difference in seconds.

Upvotes: 0

cream
cream

Reputation: 1129

That is a datetime field, not a timestamp field. You should start with reading up on what a timestamp is.

you can figure out the difference by converting to timestamp then subtracting.

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

Upvotes: 0

Related Questions