note 97510 added to function.date
| From: | dot) | Date: | Fri, 23 Apr 2010 13:34:45 +0000 |
| Subject: | note 97510 added to function.date | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168555@lists.php.net to get a copy of this message | ||
I made a function to return the difference between two dates in the following string format:
X Years, X Months, X Days.
It seems to work well, but there is a problem around leap years which results in an extra day being
added.
Can anybody clean it up for me! Thanks, Ray Arman
<?php
//function created to give a string of the difference between two dates
function stringDateDiff($beginDate, $endDate) //dates in Y-m-d format
{
$datestart=explode("-", $beginDate);
$dateend=explode("-", $endDate);
$startm=$datestart[1];
$startd=$datestart[2];
$starty=$datestart[0];
$endm=$dateend[1];
$endd=$dateend[2];
$endy=$dateend[0];
$diffyears = date('Y',strtotime(($endy)."-".$endm."-".$endd)
-strtotime($starty."-".$startm."-".$startd))
-1970;
if($diffyears<0){$diffyears=0;}
if($diffyears>0)
{
$diffmonths=date('n',strtotime(($endy+1)."-".$endm."-".$endd)
-
strtotime($endy."-".$startm."-".$startd))-1;
$diffdays=date('j',strtotime(($endy+1)."-".$endm."-".$endd)-
strtotime($endy."-".$startm."-".$startd))-1;
}
else
{
$diffmonths=date('n',strtotime(($endy)."-".$endm."-".$endd)-
strtotime($endy."-".$startm."-".$startd))-1;
$diffdays=date('j',strtotime(($endy)."-".$endm."-".$endd)
-strtotime($endy."-".$startm."-".$startd))-1;
}
$difference="$diffyears ".($diffyears==1?'Year':'Years').",
$diffmonths ".($diffmonths==1?'Month':'Months').", $diffdays
".($diffdays==1?'Day':'Days');
return $difference;
}
?>
----
Server IP: 78.110.173.36
Probable Submitter: 77.101.179.91
----
Manual Page -- http://www.php.net/manual/en/function.date.php
Edit -- https://master.php.net/note/edit/97510
Del: integrated -- https://master.php.net/note/delete/97510/integrated
Del: useless -- https://master.php.net/note/delete/97510/useless
Del: bad code -- https://master.php.net/note/delete/97510/bad+code
Del: spam -- https://master.php.net/note/delete/97510/spam
Del: non-english -- https://master.php.net/note/delete/97510/non-english
Del: in docs -- https://master.php.net/note/delete/97510/in+docs
Del: other reasons-- https://master.php.net/note/delete/97510
Reject -- https://master.php.net/note/reject/97510
Search -- https://master.php.net/manage/user-notes.php