Wednesday, 19 October 2011

How to calculate time difference in php

We can use time() function to calculate the difference between 2 dates in PHP. The time() function returns the current time as a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

The below function  returns the number of minutes, hours, days and months between 2 timestamp.


    /* 
     * Minutes  =  60       seconds
     * Hour     =  3600     seconds
     * Day      =  86400    seconds 

     * Month    =  2592000  seconds
     */


function timeAgo($time) {
   //get the time difference between current time and login time
   $timeDif=time()-$time;

   // month difference

   if (($timeDif/2592000)>=1) {
       if(floor(($timeDif/2592000))==1){
           return floor(($timeDif/2592000))." month";
       }
       else {
          return floor(($timeDif/2592000))." months";
       }
    }
    //day difference
    elseif (($timeDif/86400)>=1) {
      if(floor(($timeDif/86400)) == 1){
         return floor(($timeDif/86400))." day";
      }
      else{
         return floor(($timeDif/86400))." days";
       }
    }
    //hour difference
    elseif(($timeDif/3600)>=1) {
      if(floor(($timeDif/3600)) ==1){
         return floor(($timeDif/3600))." hour";
      }
      else{
         return floor(($timeDif/3600))." hours";
      }
    }
    // minute differnece
    elseif(($timeDif/60)>=1) {
      if(floor(($timeDif/60)) ==1){
         return floor(($timeDif/60))." minutes";
      }
      else{
         return floor(($timeDif/60))." minutes";
      }
    }else {
    return "less than 1 minute";
    }
}