1
$from_time = date('Y-m-d H:i:s');
$to_time = $row['clock'];

echo  $from_time - $to_time;

The $to_time is a time stamp in the MySQL database. $row['clock'] = 2013-10-27 13:28:01.

When I run this code, the echo always returns 0.

I am trying to get the amount of seconds between the dates.

3 Answers 3

6

You're basically trying to subtract two strings. If you echo $from_time, you can find out that the value will be something like 2013-10-27 12:49:270, and $to_time will be another string -- 2013-10-27 13:28:01.

You need to convert them into timestamps before doing the substraction:

$from_time = time();
$to_time = strtotime($row['clock']);

I recommend using the DateTime class for working with dates and times.

This is how you find the difference between two dates using DateTime class:

$from_time = new DateTime('now');
$to_time = new DateTime("2013-10-27 13:28:01");
$interval = $from_time->diff($to_time);
echo $interval->format('%h hours %i minutes %S seconds');

Output:

0 hours 31 minutes 48 seconds
Sign up to request clarification or add additional context in comments.

Comments

1

first convert $to_time to timestamp using strtotime() and then subtract,only then you will get the correct result

Comments

0

strtotime will convert a date to UNIX a timestamp,
which is in seconds and will enable you to do your calculation.
http://php.net/manual/de/function.strtotime.php

$from_time = time();
$to_time = strtotime($row['clock']);

echo  $from_time - $to_time;

1 Comment

You don't need to do strtotime(date('Y-m-d H:i:s')) -- just time() is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.