tags:

views:

303

answers:

4

I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.

I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.

        $now = new Date();
        $tzone = new Date_TimeZone($timezone);
        $now->convertTZ($tzone);
        $start = strtotime($now);
        $eob = strtotime("2009/07/02 17:00"); // Always today at 17:00

        $timediff = $eob - $start;

** Note ** It will always be less than 24 hours difference.

A: 

Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:

$start = strtotime($now);

As an alternative you could get the timestamp like this according to the documentation

$start = $now->getTime();
Tom Haigh
A: 

To do it without pear, to find the seconds 'till 17:00 you can do:

$current_time = mktime (); 
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00')); 
$timediff = $target_time - $current_time;

Not tested it, but it should do what you need.

Meep3D
A: 

I don't think you should be passing the entire Date object to strtotime. Use one of these instead;

$start = strtotime($now->getDate());

or

$start = $now->getTime();
MatW
+1  A: 

Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)

<pre>
<?php
  require "Date.php";

  $now = new Date();
  $target = new Date("2009-07-02 15:00:00");

  //Bring target to current timezone to compare. (From Hawaii to GMT)
  $target->setTZByID("US/Hawaii");
  $target->convertTZByID("America/Sao_Paulo");

  $diff = new Date_Span($target,$now);

  echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
  echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
  echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Carlos Lima