BigToach.com

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($now02);
        
$time['cd'] = substr($now22);
        
$time['cy'] = substr($now4);
        
$time['cy'] = strlen($time['cy']) > $time['cy'] : ($time['cy'] > date('y') ? '19' $time['cy'] : '20' $time['cy']);
    }
    
$time['bm'] = substr($age02);
    
$time['bd'] = substr($age22);
    
$time['by'] = substr($age4);
    
$time['by'] = strlen($time['by']) > $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


?>

Added on Jul 13th at 7 am by Scott - 2 Comments


2 Responses to age_days

Rad S. commented on Jul 31st at 5 am
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;
}
?>
Scott Roach commented on Aug 1st at 8 pm
some people were born before jan 1 1970. So this will work for people before then without adding support for negative timestamps

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: