在 PHP 中计算两个日期持续时间
例:
开始日期 : 01-01-2016
结束日期 : 31-01-2016
我得到的答案是 30 天,但我希望结果是 1 个月
更多示例:
2016-01-01 至 2016-01-31 = 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');
**