I am doing a comparasion between two dates and trying to get the year and month difference between those two dates (not the day itself).
$d1 = strtotime("2012-12");
$d2 = strtotime("2014-03");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$i++;
}
echo $i;
This outputs 15 months but how would i go about converting that into months and years?
Or if there is a better way of handling this - would love to know
you can create DateTime
objects and invoke diff
:
$date1 = new DateTime("2012-12");
$date2 = new DateTime("2014-03");
$interval = $date1->diff($date2);
echo $interval->y . " years, " . $interval->m." months, ".$interval->d." days";
spits out:
1 years, 3 months, 0 days
and if you REALLY have your heart set on using strtotime, you can get the difference in seconds like so:
$one_hour = 30*60*60;
$one_day = 24*$one_hour;
$one_month = 30*$one_day;
$one_year = 365*$one_day;
$diff = abs(strtotime('2012-12') - strtotime('2014-03'));
$years = floor($diff / $one_year);
$months = floor(($diff - $years * $one_year) / $one_month);
$days = floor(($diff - $years * $one_year - $months*$one_month)/ $one_day);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.