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

5
我有一个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小时。


$now的输出格式和您输入strtotime()函数的字符串格式相同吗?例如:"yyyy/mm/dd H:i" - Mathew
1
也许只有我一个人,但我似乎无法在PHP文档中找到“Date”类的描述。它来自哪个库? - Milen A. Radev
为什么你只将它们中的一个转换为另一个时区?难道你不应该将两者都作为本地时间或目标时区上的时间使用吗? - Carlos Lima
我应该说明的目的是要找出在另一个时区,直到17:00我还有多少时间,实际上这是关注很多其他时区的问题。 - Brian G
根据您的需求更新了我的答案,希望能对您有所帮助。 - Carlos Lima
5个回答

1

仍然给出了一些错误的值,但考虑到我使用的是旧版本的 PEAR Date,也许它对您有用,或者给您提供了修复的提示 :)

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

0

如果不使用 Pear,你可以这样找到距离下午 5 点的秒数:

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

没有测试过,但它应该能够满足你的需求。


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

    }

0
你确定将 Pear Date 对象转换为字符串再转换为时间戳的方法可靠吗?以下就是这样做的代码:

$start = strtotime($now);

作为替代方案,您可以按照文档中的方法获取时间戳。

$start = $now->getTime();

0

我认为你不应该将整个日期对象传递给strtotime函数。可以使用以下其中之一代替:

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

或者

$start = $now->getTime();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接