计算PHP中日期/时间之间的差异

时间:2009-07-02 13:19:05

标签: php

我有一个Date对象(来自Pear)并希望减去另一个Date对象以获得以秒为单位的时差。

我尝试了一些东西,但第一个只是给了我几天的差异,第二个允许我将一个固定时间转换为unix时间戳而不是Date对象。

        $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小时。

5 个答案:

答案 0 :(得分:1)

仍然提供了一些错误的值,但考虑到我有一个旧版本的PEAR日期,也许它适用于你或给你一个如何解决的提示:)

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

答案 1 :(得分:0)

您确定Pear Date对象的转换 - &gt; string - &gt;时间戳会可靠吗?这就是在这里做的:

$start = strtotime($now);

作为替代方案,您可以根据documentation

获取此类时间戳
$start = $now->getTime();

答案 2 :(得分:0)

要做到没有梨,要找到你能做到的秒数到17:00:

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

没有测试过,但它应该做你需要的。

答案 3 :(得分:0)

我认为你不应该将整个Date对象传递给strtotime。请改用其中之一;

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

$start = $now->getTime();

答案 4 :(得分:0)

也许有些人想要facebook的时间差。它告诉你“一分钟前”或“2天前”等等......这是我的代码:

function getTimeDifferenceToNowString($timeToCompare) {

        // get current time
        $currentTime = new Date();
        $currentTimeInSeconds = strtotime($currentTime);
        $timeToCompareInSeconds = strtotime($timeToCompare);

        // get delta between $time and $currentTime
        $delta = $currentTimeInSeconds - $timeToCompareInSeconds;

        // if delta is more than 7 days print the date
        if ($delta > 60 * 60 * 24 *7 ) {
            return $timeToCompare;
        }   

        // if delta is more than 24 hours print in days
        else if ($delta > 60 * 60 *24) {
            $days = $delta / (60*60 *24);
            return $days . " days ago";
        }

        // if delta is more than 60 minutes, print in hours
        else if ($delta > 60 * 60){
            $hours = $delta / (60*60);
            return $hours . " hours ago";
        }

        // if delta is more than 60 seconds print in minutes
        else if ($delta > 60) {
            $minutes = $delta / 60;
            return $minutes . " minutes ago";
        }

        // actually for now: if it is less or equal to 60 seconds, just say it is a minute
        return "one minute ago";

    }