代码之家  ›  专栏  ›  技术社区  ›  Marko

PHP日期计算

  •  2
  • Marko  · 技术社区  · 16 年前

    在PHP中,以指定格式计算两个日期之间的天数差异的最佳方法(日期格式独立方法)是什么?

    我尝试了以下功能:

    function get_date_offset($start_date, $end_date)
    {
      $start_time = strtotime($start_date);
      $end_time = strtotime($end_date);
      return round(($end_time-$start_time)/(3600*24));
    }
    

    它在Linux设备上运行正常,但在Windows strtotime下运行时返回“”。

    编辑 :

    输入日期在 MM/DD/YYYY 格式化,但我想让它接受$format作为参数。

    我只需要几天的时间。

    11 回复  |  直到 16 年前
        1
  •  6
  •   Irmantas    16 年前

    如果您不想或不能使用Zend框架或Pear包,请尝试此功能,我希望这将有助于:

    function dateDifference($date1, $date2)
    {
        $d1 = (is_string($date1) ? strtotime($date1) : $date1);
        $d2 = (is_string($date2) ? strtotime($date2) : $date2);
    
        $diff_secs = abs($d1 - $d2);
        $base_year = min(date("Y", $d1), date("Y", $d2));
    
        $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
    
        return array
        (
            "years"         => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
            "months_total"  => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
            "months"        => date("n", $diff) - 1,
            "days_total"    => floor($diff_secs / (3600 * 24)),
            "days"          => date("j", $diff) - 1,
            "hours_total"   => floor($diff_secs / 3600),
            "hours"         => date("G", $diff),
            "minutes_total" => floor($diff_secs / 60),
            "minutes"       => (int) date("i", $diff),
            "seconds_total" => $diff_secs,
            "seconds"       => (int) date("s", $diff)
        );
    }
    
        2
  •  4
  •   Paul Dixon    16 年前

    PearDate类提供了各种各样的功能,可以发现日期和大约1000种其他事物之间的差异。它的文档是 here...

        3
  •  3
  •   Vilx-    16 年前

    PHP的问题在于它没有确定的日期时间类型。您可以使用unix时间戳或内置的datetime类,但它们的功能非常有限。我希望应该有一些第三方类对日期时间计算有更广泛的支持,但我还没有找到它。

    使用Unix时间戳进行日期(而不是时间)计算也很困难。你必须放弃时间部分,但仅仅重置为00:00是不安全的,因为夏令时(DST)。DST的效果是每年有两天的时间不完全是24小时。因此,在加/减日期时,您可能会得到一个不等于3600*24的值。

    我建议找一些对所有这些东西都有适当支持的第三方课程。日期/时间计算的丑陋令人敬畏。P

        4
  •  2
  •   Ole Helgesen    16 年前

    Zend框架具有类 Zend_Date 处理“日期数学”。它通过使用bcmath扩展来绕过特定于系统的时间戳限制,或者如果不可用,则使用系统的max float值来限制时间戳。

    // example printing difference in days
    require('Zend/Date.php');
    
    $date1 = new Zend_Date();
    $date1->set(2, Zend_Date::MONTH);
    $date1->set(27, Zend_Date::DAY);
    $date1->set(2008, Zend_Date::YEAR);
    
    $date2 = new Zend_Date();
    $date2->set(3, Zend_Date::MONTH);
    $date2->set(3, Zend_Date::DAY);
    $date2->set(2008, Zend_Date::YEAR);
    
    echo ($date2->getTimestamp() - $date1->getTimestamp()) / (3600*24);
    
        5
  •  1
  •   csl    16 年前

    我不知道该考虑什么 最好的 ,因为在PHP中没有内置函数来执行此操作,但是有些人已经使用了 gregoriantojd() ,例如在 this forum post .

        6
  •  1
  •   Radek    16 年前

    gregoriantojd()提供与使用strtotime()相同的结果,有关如何执行的信息,请参阅此blogpost:

    http://www.phpro.org/examples/Calculate-Age-With-PHP.html

        7
  •  1
  •   ftdysa    16 年前

    以下是我的作品。相信我在php.net文档的某个地方找到了它。

    *编辑汪汪,没看到CSL的帖子。这是他链接的确切功能,一定是我找到它的地方。;)

    //Find the difference between two dates
    function dateDiff($startDate, $endDate)
    {
        // Parse dates for conversion
        $startArry = date_parse($startDate);
        $endArry = date_parse($endDate);
    
        // Convert dates to Julian Days
        $start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
        $end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
    
        // Return difference
        return round(($end_date - $start_date), 0);
    }
    
        8
  •  1
  •   ivarne    15 年前

    为了显示一个事件的持续时间,我试图计算两个日期之间的差异。如果事件的持续时间为星期五17:00至星期日15:00,则针对该问题给出的大多数函数都将失败。我的目标是找出日期之间的区别,比如:

    date('Ymd',$end)-date('Tmd',$begining);
    

    但这很可能会失败,因为一年没有99个月,一个月没有99天。我可以将日期字符串转换为unix时间戳,然后除以60*60*12,但有些日子的小时数要么大要么小,有时会有一个闰秒。所以我使用getDate()创建了自己的函数,它返回一个关于时间戳的innformation数组。

    /*
     * datediff($first,$last)
     * $first - unix timestamp or string aksepted by strtotime()
     * $last - unix timestamp or string aksepted by strtotime()
     * 
     * return - the difference in days betveen the two dates
     */
    function datediff($first,$last){
     $first = is_numeric($first) ? $first : strtotime($first);
     $last  = is_numeric($last ) ? $last  : strtotime($last );
     if ($last<$first){
      // Can't calculate negative difference in dates
      return -1;
     }
     $first = getdate($first);
     $last =  getdate($last );
     // find the difference in days since the start of the year
     $datediff = $last['yday'] - $first['yday'];
     // if the years do not match add the appropriate number of days.
     $yearCountedFrom = $first['year'];
     while($last['year'] != $yearCountedFrom ){
      // Take leap years into account
      if( $yearCountedFrom % 4 == 0 && $yearCountedFrom != 1900 && $yearCountedFrom != 2100 ){
       //leap year
       $datediff += 366;
      }else{
       $datediff += 365;
      }
      $yearCountedFrom++;
     }
     return $datediff;
    }
    

    关于gregoriantojd()函数,它可能会工作,但是我有点不安,因为我不理解它是如何工作的。

        9
  •  0
  •   dirtside    16 年前

    伙计们,我们不要设计得太高。

    $d1 = strtotime($first_date);
    $d2 = strtotime($second_date);
    $delta = $d2 - $d1;
    $num_days = ($delta / 86400);
    
        10
  •  0
  •   James - Php Development    15 年前

    使用PHP计算两个日期(和时间)之间的差异。下一页提供了一系列不同的方法(共7种),用于使用PHP执行日期/时间计算,以确定两个日期之间的时间差(小时、弹药)、天、月或年。

    Php Date Time - 7 Methods to Calculate the Difference between 2 dates

        11
  •  0
  •   John Conde    12 年前

    php 5.2介绍了 DateTime DateInterval 使这变得容易的类:

    function get_date_offset($start_date, $end_date)
    {
        $start_time = new DateTime($start_date);
        $end_time   = new DateTime($end_date);
        $interval   = $end_time->diff($start_time);
        return $interval->format('%a days');
    }