簡體   English   中英

如何計算 01-01-2016 到 31-01-2016 的持續時間。 用 PHP 1 個月獲得答案

[英]How to Calculate duration 01-01-2016 to 31-01-2016 . get answer 1 month in PHP

在 PHP 中計算兩個日期之間的持續時間

例子 :

開始日期 : 01-01-2016

結束日期 : 31-01-2016

我得到的答案是 30 天,但我想要的結果是 1 個月

更多例子:

01-01-2016 至 31-01-2016 = 1 個月

01-02-2016 至 29-02-2016 =1 個月

01-03-2016 至 31-03-2016 =1 個月

顯示在..

<?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);
?>

我認為這會對你有所幫助。

這是我嘗試過的。

找到第一個日期的月份的第一天和最后一天,並將它們與給定的日期進行比較。 如果它們匹配,它會打印“1 個月”,否則它會打印“n 天”之類的天數。

$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;
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');

**

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM