如何使用PHP将一个日期减去另一个日期

时间:2012-05-22 10:29:37

标签: php

我想使用php将一个日期减去另一个日期,并以天 - 小时 - 分 - 秒格式显示结果。我是怎么用ph​​p做的。我尝试使用时间戳,但它没有给出正确的值。请给出建议

例如:从2012-04-27 19:30:56到2012-04-27 19:37:56

我使用了这段代码

if(strtotime($history['datetimestamp']) > strtotime($lasttime)) {

                 $totalelapsed1 = (strtotime($history['datetimestamp'])-strtotime($lasttime)); 




                     if($totalelapsed1 > 60 ) {
                         $sec = $totalelapsed1%60;
                         $min = round($totalelapsed1/60 , 0);

                         $minute = $min + $minute;
                         $second = $sec + $second;

                        // echo $min. " min " .$sec." sec";

                     } else {
                         //echo "0 min " . $totalelapsed1." sec";

                         $minute = 0 + $minute;
                         $second = $totalelapsed1 + $second;

                    }



                } else {
                     $minute = 0 + $minute;
                     $second = 0 + $second;
                    // echo "0 min 0 sec";
                }

4 个答案:

答案 0 :(得分:10)

how to subtract two dates and times to get difference来自VolkerK

  

你必须这样使用: -

<?php

//$now = new DateTime(); // current date/time
$now = new DateTime("2010-07-28 01:11:50");
$ref = new DateTime("2010-07-30 05:56:40");
$diff = $now->diff($ref);
printf('%d days, %d hours, %d minutes', $diff->d, $diff->h, $diff->i);
prints 2 days, 4 hours, 44 minutes
     

请参阅http://docs.php.net/datetime.diff

     

编辑:但您也可以将问题更多地转移到数据库端,例如通过在表中存储过期日期/时间然后执行查询   ...... WHERE key='7gedufgweufg' AND expires<Now()   许多rdbms对日期/时间算法有合理/良好的支持。

链接网址: - how to subtract two dates and times to get difference

http://www.webpronews.com/calculating-the-difference-between-two-dates-using-php-2005-11

答案 1 :(得分:5)

我建议使用DateTime和DateInterval对象。

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "days difference ".$interval->d." days "; 

阅读更多php DateTime::diff manual

答案 2 :(得分:0)

尝试使用DateTime:diff()

该页面提供了示例。

答案 3 :(得分:0)

此脚本解决了我的问题

$date1 = date("d-m-Y H:i:s",strtotime($date1));

$date2 = date("d-m-Y H:i:s",strtotime($lasttime));

$diff = abs(strtotime($date2) - strtotime($date1));

$years   = floor($diff / (365*60*60*24));  $months  = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));  $days    = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

$hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));  $minuts  = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);  $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60)); 

printf("%d years, %d months, %d days, %d hours, %d minuts\n, %d seconds\n", $years, $months, $days, $hours, $minuts, $seconds);