PHP Snippets
age_days
Information
(PHP Version >= 3.0.6)Functions used in this snippet: str_replace, date, substr, strlen.
Description
int age_days( mixed age[, mixed now] )
Takes a date and translates it into how many days it has been since the current time. If the optional now parameter is set, the age will be in days since now.
The date must be formatted in one of the following ways.
01/05/83
010583
01051983
01-05-83
01 05 1983
01,05,83
The year can either be 2 or 4 digits, but it must go month then year and each must be 2 digits long.
Snippet
<?php
function age_days($age, $now=NULL){
$time = array();
$age = str_replace(array('-', '\\', '/', ' ', ','), '', $age);
if($now === NULL){
$time['cd'] = date('d');
$time['cm'] = date('m');
$time['cy'] = date('Y');
}else{
$now = str_replace(array('-', '\\', '/', ' ', ','), '', $now);
$time['cm'] = substr($now, 0, 2);
$time['cd'] = substr($now, 2, 2);
$time['cy'] = substr($now, 4);
$time['cy'] = strlen($time['cy']) > 3 ? $time['cy'] : ($time['cy'] > date('y') ? '19' . $time['cy'] : '20' . $time['cy']);
}
$time['bm'] = substr($age, 0, 2);
$time['bd'] = substr($age, 2, 2);
$time['by'] = substr($age, 4);
$time['by'] = strlen($time['by']) > 3 ? $time['by'] : ($time['by'] > date('y') ? '19' . $time['by'] : '20' . $time['by']);
$time['fd'] = $time['cd'] - $time['bd'];
if($time['fd'] < 0){
$time['fd'] = 31 + $time['fd'];
$time['cm']--;
}
$time['fm'] = $time['cm'] - $time['bm'];
if($time['fm'] < 0){
$time['fm'] = 12 + $time['fm'];
$time['cy']--;
}
$time['fy'] = $time['cy'] - $time['by'];
return (($time['fy'] * 365) + ($time['fm'] * 31) + $time['fd']);
}
?>
Example
age_days Can be used in the following way:
<?php
echo age_days('110583'); // age in days (as of 07/13/05 it is 7921)
echo age_days('11-05-1983', '07-13-2005'); // 7921
?>
2 Responses to age_days
I'm confused as to why you wouldn't just do something like:
<?php
function age_days($start, $end = null) {
if ($end === null) {
$end = time();
}
return ($end - $start) / 60 / 60 / 24;
}
?>
some people were born before jan 1 1970. So this will work for people before then without adding support for negative timestamps