在PHP程序中,很多时候都会遇到处理日期时间的问题,比如:两个时间相距天数、还有多长时间过期、到指定日期相差多少天等。
本文主要介绍3个PHP日期计算处理函数,分别是计算到指定日期还有多少天、计算两个日期相差多少天、两个日期的时间差,非常简单实用。
一、php计算到指定日期还有多少天?
function countdays($d) { $olddate = substr($d, 4); $newdate = date(Y) ."".$olddate; $nextyear = date(Y)+1 ."".$olddate; if($newdate > date("Y-m-d")) { $start_ts = strtotime($newdate); $end_ts = strtotime(date("Y-m-d")); $diff = $end_ts - $start_ts; $n = round($diff / 86400); $return = substr($n, 1); return $return; } else { $start_ts = strtotime($nextyear); $end_ts = strtotime(date("Y-m-d")); $diff = $end_ts - $start_ts; $n = round($diff / 86400); $return = substr($n, 1); return $return; } }
二、php计算两个日期相差多少天
function diffBetweenTwoDays ($day1, $day2) { $second1 = strtotime($day1); $second2 = strtotime($day2); if ($second1 < $second2) { $tmp = $second2; $second2 = $second1; $second1 = $tmp; } return ($second1 - $second2) / 86400; } $day1 = "2014-10-27"; $day2 = "2015-08-04"; $diff = diffBetweenTwoDays($day1, $day2); echo $diff."\n";
三、php计算两个日期时间差
实现了类似微博中的多少天、多少月、多少年功能。
<?php 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); $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); } ?>
声明:如需转载,请注明来源于www.webym.net并保留原文链接:http://www.webym.net/jiaocheng/889.html