1.解决PHP如何判断两个日期之间相距的天数,并可换算为月、年。
DiffDate("2021-01-06","2023-06-16");// 计算两个日期相差 年 月 日 function DiffDate($date1, $date2) { if (strtotime($date1) > strtotime($date2)) { $ymd = $date2; $date2 = $date1; $date1 = $ymd; } list($y1, $m1, $d1) = explode('-', $date1); list($y2, $m2, $d2) = explode('-', $date2); $y = $m = $d = $_m = 0; $math = ($y2 - $y1) * 12 + $m2 - $m1; //相差总月数 $y = round($math / 12); //相差年数 $m = intval($math % 12); //相差月数 $mm = $math; //相差总月数 $d = (mktime(0, 0, 0, $m2, $d2, $y2) - mktime(0, 0, 0, $m2, $d1, $y2)) / 86400; if ($d < 0) { $m -= 1; $d += date('j', mktime(0, 0, 0, $m2, 0, $y2)); } $m < 0 && $y -= 1; return array($y, $m, $d,$mm); }
2. 使用strtotime()后的数值直接相减,计算相差总天数 小时 秒 计算
$one = strtotime('2011-12-08 07:02:40');//开始时间 时间戳$tow = strtotime('2011-12-25 00:00:00');//结束时间 时间戳$cle = $tow - $one; //得出时间戳差值$d = floor($cle/3600/24);$h = floor(($cle%(3600*24))/3600); //%取余$m = floor(($cle%(3600*24))%3600/60);$s = floor(($cle%(3600*24))%60);echo "两个时间相差 $d 天 $h 小时 $m 分 $s 秒"
3.计算两个日期相隔多少年,多少月,多少天 ,使用php类库
function diffDate($date1,$date2){ $datetime1 = new \DateTime($date1); $datetime2 = new \DateTime($date2); $interval = $datetime1->diff($datetime2); $time['y'] = $interval->format('%Y'); $time['m'] = $interval->format('%m'); $time['d'] = $interval->format('%d'); $time['h'] = $interval->format('%H'); $time['i'] = $interval->format('%i'); $time['s'] = $interval->format('%s'); $time['a'] = $interval->format('%a'); // 两个时间相差总天数 return $time;} # 使用实例$sss = diffDate('2020-01-21 12:30:30', '2023-06-18 15:00:00');print_r($sss);
4.方法3
function diffDate($date1,$date2){ $datestart= date('Y-m-d',strtotime($date1)); if(strtotime($datestart)>strtotime($date2)){ $tmp=$date2; $date2=$datestart; $datestart=$tmp; } list($Y1,$m1,$d1)=explode('-',$datestart); list($Y2,$m2,$d2)=explode('-',$date2); $Y=$Y2-$Y1; $m=$m2-$m1; $d=$d2-$d1; if($d<0){ $d+=(int)date('t',strtotime("-1 month $date2")); $m--; } if($m<0){ $m+=12; $y--; } if($Y == 0){ return $m.'个月'.$d.'天'; }elseif($Y == 0 && $m == 0){ return $d.'天'; }else{ return $Y.'年'.$m.'个月'.$d.'天'; } } $catdata="2002-09-28"; //计算时间 echo diffDate($catdata,date('Y-m-d',time()));
来源地址:https://blog.csdn.net/qq_32450471/article/details/131277529