note 101771 added to function.date-diff

From: Date: Mon, 10 Jan 2011 17:26:57 +0000
Subject: note 101771 added to function.date-diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-175607@lists.php.net to get a copy of this message
Here is how I solved the problem of missing date_diff function with php versions below 5.3.0 The function accepts two dates in string format (recognized by strtotime() hopefully), and returns the date difference in an array with the years as first element, respectively months as second, and days as last element. It should be working in all cases, and seems to behave properly when moving through February. <? function dateDifference($startDate, $endDate) { $startDate = strtotime($startDate); $endDate = strtotime($endDate); if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate) return false; $years = date('Y', $endDate) - date('Y', $startDate); $endMonth = date('m', $endDate); $startMonth = date('m', $startDate); // Calculate months $months = $endMonth - $startMonth; if ($months <= 0) { $months += 12; $years--; } if ($years < 0) return false; // Calculate the days $measure = ($months == 1) ? 'month' : 'months'; $days = $endDate - strtotime('+' . $months . ' ' . $measure, $startDate); $days = date('z', $days); return array($years, $months, $days); } ?> ---- Server IP: 82.177.164.100 Probable Submitter: 212.87.1.131 ---- Manual Page -- http://www.php.net/manual/en/function.date-diff.php Edit -- https://master.php.net/note/edit/101771 Del: integrated -- https://master.php.net/note/delete/101771/integrated Del: useless -- https://master.php.net/note/delete/101771/useless Del: bad code -- https://master.php.net/note/delete/101771/bad+code Del: spam -- https://master.php.net/note/delete/101771/spam Del: non-english -- https://master.php.net/note/delete/101771/non-english Del: in docs -- https://master.php.net/note/delete/101771/in+docs Del: other reasons-- https://master.php.net/note/delete/101771 Reject -- https://master.php.net/note/reject/101771 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#175607) next »