计算PHP中日期/时间之间的差异 [英] Calculate the difference between date/times in PHP

查看:106
本文介绍了计算PHP中日期/时间之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Date对象(来自Pear),想减去另一个Date对象,以秒为单位获取时差.

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

我已经尝试了一些方法,但是第一个方法只是给了我几天的时间,而第二个方法则允许我将一个固定的时间转换为unix时间戳,而不是Date对象.

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;

**注意**始终少于24小时.

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

推荐答案

仍然给出了一些错误的值,但是考虑到我有一个较旧的PEAR Date版本,也许它对您有用,或者给您提示如何解决:)

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>

这篇关于计算PHP中日期/时间之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆