Monday, 13 August 2018

Time Calculator In PHP

Use the following function to work out how long it has been since an event in years, months, weeks, days, hours, minutes and seconds.
  1. function getAge($year,$month,$day,$hour=0,$minute=0,$second=0){
  2. $age = mktime($hour,$minute,$second,$month,$day,$year);
  3. $age = time()-$age;
  4. return array('years'=>$age/60/60/24/365,
  5. 'months'=>$age/60/60/24/12,
  6. 'weeks'=>$age/60/60/24/7,
  7. 'days'=>$age/60/60/24,
  8. 'hours'=>$age/60/60,
  9. 'minutes'=>$age/60,
  10. 'seconds'=>$age);
  11. }
The practical use of this function is that you can work out how old someone is from their birthday. Here is an example of the function in use.
  1. // someone's birthday
  2. echo ''.print_r(getAge(1984,10,4),true).'';
Which would output the following:
  1. Array
  2. (
  3. [years] => 23.721673198884
  4. [months] => 721.53422646605
  5. [weeks] => 1236.9158167989
  6. [days] => 8658.4107175926
  7. [hours] => 207801.85722222
  8. [minutes] => 12468111.433333
  9. [seconds] => 748086686
  10. )
Any function like this can be tested by putting in the current time, if you get zero across the board then the function works.

0 comments:

Post a Comment