Monday 8 July 2013

calculate age using php

calculate age using php


In this php tip let us check how to calculate age using php. Calculating age is very importent if you are devloping any website that are dealing with displaying users age imformation. So let us create a php function which will return a persons current age when we give the persons date of birth. You can also check how to

create simple php calendar at here.




function calculate_age($inpDate)

{


        $nowda=date('Y-m-d');


        if($nowda >= $inpDate)


        {


          list($inpYear, $inpMonth, $inpDay) = explode("-", $inpDate);


          $numOfDays = cal_days_in_month(CAL_GREGORIAN, $inpMonth, $inpYear);


          if($inpDay > $numOfDays) {


          $inpDay = $numOfDays;


          }


          if($inpMonth > 12) {


          $inpMonth = 12;


          }


          $diffYear = date("Y") - $inpYear;


          $diffMonth = date("m") - $inpMonth;


          $diffDay = date("d") - $inpDay;


          if($diffMonth < 0) {


          $diffYear -= 1;


          $diffMonth += 12;


          }


          if($diffDay < 0) {


          $diffMonth -= 1;


          $diffDay += $numOfDays;


          }



          if($diffYear>0){


          if($diffYear==1){


          $year=$diffYear. " year";


          }


          else {$year=$diffYear." years";}


          }


          elseif($diffYear<=0&&$diffMonth>0){


          if($diffMonth==1){


          $year=$diffMonth." month";


          }


          else {$year=$diffMonth." months";}


          }


          elseif($diffYear<=0&&$diffMonth<=0&&$diffDay>0){


          if($diffDay==1){


          $year= $diffDay." day";


          }


          else {$year= $diffDay." days";}


          }


          else{


          $year="--";


          }



          return $year;



        }



        else{


        $year="--";


        return $year;


        }


}


//usage of the function


echo $res1=calculate_age('1995-05-12');


echo "</br>";


echo $res2=calculate_age('1990-02-20');


echo "</br>";


echo $res3=calculate_age('1900-01-12');


echo "</br>";


echo $res3=calculate_age('2013-01-12');





So by using the above function you can easily calculate and display a persons age using php. This function will return age as years if age is equal or grater than 1. If age is less than 1 year the function will return result in months. and if the age is less than a month the function will return age in days. Also I created the function in a way that it will accept input date in a formatt of ‘year-month-day’ (Y-m-d). So you need to give date in this format to the function, or you can change the code to change the format of the date.

So I hope this will help you to show age of a person when creating website that are dealing with displaying or using users age information.



calculate age using php

No comments:

Post a Comment