note 88030 deleted from function.date by derick
| From: | derick@php.net | Date: | Sun, 22 Mar 2009 18:44:51 +0000 |
| Subject: | note 88030 deleted from function.date by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-152295@lists.php.net to get a copy of this message | ||
Note Submitter: gblues at gmail dot com
----
There are a ton of snippets here and elsewhere on the Internet that are supposed to calculate time
between two dates (or more precisely, between two UNIX timestamps), but none of them take leap years
into account.
I wrote this snippet as a means of accurately calculating someone's age relative to the current
time. This could be easily expanded to factor in months and days, but I will leave that as an
exercise for the reader.
<?php
/*
* getAge() by Nathan Strong
* $start_ts is a UNIX timestamp sometime in the past.
* This function will not work with dates prior to epoch (EPOCH FAIL!)
*/
function getAge($start_ts)
{
$end_ts = time();
$anniversary = date('z', $start_ts);
$days_in_year = date('L', $start_ts) ? 366 : 365;
$sec_per_day = 86400; // 60 * 60 * 24
$diff = $end_ts - $start_ts;
$diff -= $diff % $sec_per_day; // discard misc seconds
$days = $diff / $sec_per_day; // number of days to iterate through;
if( $diff < 0 )
return false; // $start_ts is in the future!
if( $days < $days_in_year ) // less than 1 year old; don't need to loop
return 0;
$years = 0;
do {
// add the remaining days left in the current year first.
$left_in_year = $days_in_year - $anniversary;
if( $days < $left_in_year )
$left_in_year = $days;
$start_ts += $sec_per_day * $left_in_year;
$days -= $left_in_year;
// are there enough days remaining to make it to the next birthday?
if( $days > $anniversary )
{
$years++; // increment years;
$to_anniv = $anniversary;
} else {
$to_anniv = $days;
}
// add the days remaining to either the next birthday, or today's date, whichever
// is closer.
$start_ts += $sec_per_day * $to_anniv;
$days -= $to_anniv;
// reevaluate $days_in_year so that leap year is taken into account.
$days_in_year = date('L', $start_ts) ? 366 : 365;
} while( $days > 0 );
// return the result.
return $years;
}
?>