【问题标题】:How to get duration of days between today and 2011-5-20 in days by PHP? [duplicate]如何通过 PHP 获取今天和 2011-5-20 之间的天数? [复制]
【发布时间】:2011-05-20 07:47:52
【问题描述】:

可能重复:
How to count days between two dates in PHP?

好像只有javascript的版本,PHP的呢?

【问题讨论】:

  • @Shakti Singh,我的问题是在today 和另一天之间计算,所以有点不同..
  • 完全没有差异。通过date('Y-m-d') 函数获取今天的日期

标签: php date


【解决方案1】:

几乎直接取自我几周前写的一篇文章:Working with Date and Time in PHP

$today = new DateTime();
$ref = new DateTime("2011-05-20");

$diff = $today->diff($ref);
echo "the difference is {$diff->days} days" . PHP_EOL;

【讨论】:

    【解决方案2】:

    计算它们相差的秒数,您可以轻松计算天数。

    $oFirstDate = new DateTime($sDateFormat);
    $oSecondDate = new DateTime($sDateFormat2);
    $iSeconds = $oFirstDate->getTimeStamp() - $oSecondDate->getTimeStamp();
    $iDays = $iSeconds / 60 / 60 / 24;
    

    【讨论】:

      【解决方案3】:

      我同意 Shakti 的观点;只需进行少量更改,the other question 中的脚本就可以为您工作:

      <?php
      $datetime1 = date_create( date( 'Y-m-d' ) );
      $datetime2 = date_create('2011-05-21');
      $interval = date_diff($datetime1, $datetime2);
      
      echo $interval->days . " days difference.";
      

      【讨论】:

        【解决方案4】:

        嗯,我有一个通用的函数来处理这样的事情:

        function timediffIn($time, $unit, $human = False){
        
            $tokens = array (
                'years'   => 31536000,
                'months'  => 2592000,
                'weeks'   => 604800,
                'days'    => 86400,
                'hours'   => 3600,
                'minutes' => 60,
                'seconds' => 1
            );
        
            if(!array_key_exists($unit, $tokens)){
                if ($human) print "No such unit: $unit\n";
                return FALSE;   
            } 
            if(!strtotime($time)){
                if ($human) print "$time does not translate into a valid time\n";
                return FALSE;
            }
        
            $elapsed = time() - strtotime($time);
        
            $interval = $tokens[$unit];
            if($human){
                print "It has been " . floor($elapsed / $interval) . " $unit since $time\n";
            }
            return floor($elapsed / $interval);
        
        }
        

        HTH

        【讨论】:

        • 显然,“human”参数是用于调试目的/命令行脚本——你可以安全地删除所有与它有关的内容。
        猜你喜欢
        • 1970-01-01
        • 2021-04-30
        • 2013-11-29
        • 2022-01-13
        • 2011-06-14
        • 2018-04-14
        • 1970-01-01
        • 1970-01-01
        • 2020-07-07
        相关资源
        最近更新 更多