Función ¿Cuánto tiempo has vivido? con PHP

Interesante función que he usado muchas veces para saber en detalle en tiempo de vida de una persona. Bastará con colocar la fecha de nacimiento de la persona y el código hará el resto:

<?php
class Age
{
var $age = '';

function calculateAge($iTimestamp)
{
$iDiffYear = date('Y') - date('Y', $iTimestamp);
$iDiffMonth = date('n') - date('n', $iTimestamp);
$iDiffDay = date('j') - date('j', $iTimestamp);

// If birthday has not happen yet for this year, subtract 1.
if ($iDiffMonth < 0 || ($iDiffMonth == 0 && $iDiffDay < 0))
{
$iDiffYear--;
}

$this->age = $iDiffYear;
}

function getAge()
{
return $this->age;
}

function get_rank($rank)
{
$last = substr( $rank, -1 );
$seclast = substr( $rank, -2, -1 );
if( $last > 3 || $last == 0 ) $ext = 'th';
else if( $last == 3 ) $ext = 'rd';
else if( $last == 2 ) $ext = 'nd';
else $ext = 'st';

if( $last == 1 && $seclast == 1) $ext = 'th';
if( $last == 2 && $seclast == 1) $ext = 'th';
if( $last == 3 && $seclast == 1) $ext = 'th';

return $rank.$ext;
}

}

$dob = '1983-09-27'; // fecha de nacimiento
$dob2 = explode("-",$dob);

$dob_hour = 18; // 24 hour format
$dob_min = 41;
$dob_sec = 0;

$d = getdate(); // Current date

$year=$d['year'];
$mon=$d['mon'];
$mday=$d['mday'];

$hour = $d['hours'];
$min = $d['minutes'];
$sec = $d['seconds'];


$d1=mktime($dob_hour,$dob_min,$dob_sec,$dob2[1],$dob2[2],$dob2[0]);
$d2=mktime($hour,$min,$sec,$mon,$mday,$year);

$obj = new Age;

$obj->calculateAge(mktime($dob_hour,$dob_min,$dob_sec,$dob2[1],$dob2[2],$dob2[0]));

$age = $obj->getAge();
$rank = $obj->get_rank($age+1);

echo 'Tu edad: '.$age;

echo '<br><br>';
echo '<b>Tu has vivido:</b> <br><br>';

echo "A&ntilde;os: ".floor(($d2-$d1)/31536000) . "<br>";
echo "Meses: ".floor(($d2-$d1)/2628000) . "<br>";
echo "Semanas: ".floor(($d2-$d1)/604800) . "<br>";
echo "Dias: ".floor(($d2-$d1)/86400) . "<br><br>";

echo "Horas: ".floor(($d2-$d1)/3600) . "<br>";
echo "Minutos: ".floor(($d2-$d1)/60) . "<br>";
echo "Segundos: " .($d2-$d1). "<br><br>";
?>

Espero les sea útil como me lo ha sido a mi.

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Wanderz Blog by Crimson Themes.