Php subtract current time from string

Hello forums

How do I substract the current time from a string and return me the number of hours.

$t = '2010-05-06 15:33:45';
$s =  	strtotime($t);
$h = floor(time() - $s / 60 );
echo  $h;

^ didn’t work :frowning:

time() returns a unix timestamp, which is represents seconds.
–How many seconds are in an hour?

Like when you do math on paper, certain arithmetic operators have higher precedence, and must be evaluated first unless parenthesis are used to force the order of operations.

6 - 4 / 2 = ?
–What’s the correct result? 4 or 1?

Ok I see however how do I evaluate arithmetic operators inside a mysql query. Here’s my scenario:

I want to get the hour difference of s_in and s_out from the table and insert it to the column hours_today
here’s my query to get the seconds difference of the two columns

$q = mysql_query("SELECT UNIX_TIMESTAMP(s_out) - UNIX_TIMESTAMP(s_in) AS dif FROM sd_record WHERE id = 1");

and to convert it to hours I need to : floor(dif / (60 * 60)) it. How then can I do that?


I might need a new thread for this over at mysql forums

        (UNIX_TIMESTAMP(s_out) - UNIX_TIMESTAMP(s_in)) / 3600
       ) AS hrs
  FROM ...

But, most databases have a lot of date and time manipulation capabilities. Another one of many ways

SELECT HOUR(TIMEDIFF(s_out, s_in)) AS hrs
  FROM ...

If you wanna update the whole table

UPDATE sometable
   SET hours_today = HOUR(TIMEDIFF(s_out, s_in))

The column seems a bit redundant though, because it stores information that already exists(just needs to be calculated).

I need to get the total number of hours by adding all the rows in the hours_today latter

Anyway I, trying to make your second query work but it’s throwing me syntax errors:

$q = mysql_query(“SELECT HOUR(TIMEDIF(s_out, s_in)) AS hrs FROM sd_record WHERE id = 1”);

oops sori I just need to remove the extra space TIMEDIFF(s_out,s_in)

I see that this one is much better. it will enter the hour including the mins and seconds

UPDATE sometable
   SET hours_today = HOUR(TIMEDIFF(s_out, s_in))

Question: How then can I get the total number of hours in all the rows in the hours_today column?


OK here’s to get the total

$q = mysql_query("SELECT SUM(hours_today) AS tot FROM sd_record");

Thanx crmalibu you are a great help

SELECT SUM(hours_today) AS total


SELECT SUM(HOUR(TIMEDIFF(s_out, s_in))) AS total