HippoDuck
HippoDuck

Reputation: 2194

PHP - Difference between 2 dates, returning 0

$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.

Upvotes: 1

Views: 78

Answers (3)

Kiran Gopalakrishnan
Kiran Gopalakrishnan

Reputation: 322

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

Upvotes: 1

Amal Murali
Amal Murali

Reputation: 76656

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

Upvotes: 6

gherkins
gherkins

Reputation: 14983

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;

Upvotes: 0

Related Questions