如何计算持续时间01-01-2016到31-01-2016。在PHP中获得答案1个月

问题描述 投票:-1回答:3

在PHP中计算两个日期之间的持续时间

示例:

开始日期:01-01-2016

结束日期:31-01-2016

我得到的答案是30天,但我希望结果是1个月

更多示例:

2016年1月1日至2016年1月31日= 1个月

2016年1月1日至2016年2月29日= 1个月

2016年1月3日至2016年3月31日= 1个月

在..上显示

php date duration
3个回答
0
投票
<?php
$date1 = '2000-01-20';
$date2 = '2000-02-20';

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);

$month1 = date('m', $ts1);
$month2 = date('m', $ts2);

echo $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
?>

我认为这会对您有所帮助。


0
投票

这是我尝试过的。

查找第一个日期的月份的第一天和最后一天,并将其与给定的日期进行比较。如果它们匹配,则显示“ 1 month”,否则显示“ n days”之类的天数。

$date1 = "2016-02-01";
$date2 = "2016-02-29";

$output = "";
if ($date1 == date("Y-m-01", strtotime($date1)) && $date2 == date("Y-m-t", strtotime($date1))) {
    $output = "1 month";
} else {
    $output = ((strtotime($date2) - strtotime($date1)) / 86400 + 1) . " days";
}

echo $output;

0
投票
class shahjadclass {




    public function getduration($postdate) {


        /*  $postdate is the date where the post was created  */

$assigned_time = date("Y-m-d h:i:sa");       
$d1 = new DateTime($assigned_time);
$d2 = new DateTime($postdate);
$interval = $d2->diff($d1);
$datestring='';
if($interval->y>0){
$datestring=$interval->format('%y Years ago') ;
}elseif ($interval->m>0) {
$datestring=$interval->format('%m Months ago') ;
}elseif ($interval->d>0) {
$datestring=$interval->format('%d Days ago') ;                                        
}elseif ($interval->h>0) {
$datestring=$interval->format('%h Hours ago') ;                          
}elseif($interval->i>0){
$datestring=$interval->format('%i Min ago') ;  
}else{
$datestring=$interval->format('%s Sec ago') ;
}

 return $datestring;  
    }





}

**

用法

require_once('shahjadclass.php');
 $myfunctions = new shahjadclass();

获得输出

 $datestring=$myfunctions->getduration('createdon');

**

© www.soinside.com 2019 - 2024. All rights reserved.