note 88030 added to function.date

From: Date: Tue, 06 Jan 2009 20:37:12 +0000
Subject: note 88030 added to function.date
Groups: php.notes 
Request: Send a blank email to php-notes+get-148904@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 71.37.169.191 ---- Manual Page -- http://www.php.net/manual/en/function.date.php Edit -- https://master.php.net/note/edit/88030 Del: integrated -- https://master.php.net/note/delete/88030/integrated Del: useless -- https://master.php.net/note/delete/88030/useless Del: bad code -- https://master.php.net/note/delete/88030/bad+code Del: spam -- https://master.php.net/note/delete/88030/spam Del: non-english -- https://master.php.net/note/delete/88030/non-english Del: in docs -- https://master.php.net/note/delete/88030/in+docs Del: other reasons-- https://master.php.net/note/delete/88030 Reject -- https://master.php.net/note/reject/88030 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148904) next »