Advertisement
l3rady

WordPress - new human_time_diff() function

Apr 16th, 2012
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.67 KB | None | 0 0
  1.         function human_time_diff( $from, $to = '' )
  2.         {
  3.             $chunks = array(
  4.                 array( 60 * 60 * 24 * 365 , '%s year', '%s years' ),
  5.                 array( 60 * 60 * 24 * 30 , '%s month', '%s months' ),
  6.                 array( 60 * 60 * 24 * 7, '%s week', '%s weeks' ),
  7.                 array( 60 * 60 * 24 , '%s day', '%s days' ),
  8.                 array( 60 * 60 , '%s hour', '%s hours' ),
  9.                 array( 60 , '%s minute', '%s minutes' ),
  10.                 array( 1 , '%s second', '%s seconds' ),
  11.             );
  12.  
  13.             if ( empty( $to ) )
  14.                     $to = time();
  15.  
  16.             $diff = (int) abs( $to - $from );
  17.  
  18.  
  19.             for ( $i = 0, $j = count( $chunks ); $i < $j; $i++)
  20.             {
  21.                 $seconds = $chunks[$i][0];
  22.                 $name1 = $chunks[$i][1];
  23.                 $name2 = $chunks[$i][2];
  24.  
  25.                 if ( ( $count = floor( $diff / $seconds ) ) != 0)
  26.                     break;
  27.             }
  28.  
  29.             $since = sprintf( _n( $name1, $name2, $count ), $count );
  30.  
  31.             $i++;
  32.  
  33.             if ( $i < $j )
  34.             {
  35.                 $seconds_p2 = $chunks[$i][0];
  36.                 $name1 = $chunks[$i][1];
  37.                 $name2 = $chunks[$i][2];
  38.  
  39.                 if ( ( $count = floor( ( $diff - ( $seconds * $count ) ) / $seconds_p2 ) ) != 0 )
  40.                 {
  41.                     if( is_rtl() )
  42.                         $since = sprintf( _n( $name1, $name2, $count ), $count ) ." ". $since;
  43.                     else
  44.                         $since = $since. " " . sprintf( _n( $name1, $name2, $count ), $count );
  45.                 }
  46.             }
  47.  
  48.             return $since;
  49.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement