Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the difference between date/times in PHP

Tags:

php

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.

like image 768
Brian G Avatar asked Nov 15 '22 15:11

Brian G


1 Answers

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>
like image 66
Carlos Lima Avatar answered Dec 21 '22 21:12

Carlos Lima