Advertisement
Guest User

PHP getRelativeDate

a guest
Jun 25th, 2010
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.44 KB | None | 0 0
  1. /*
  2.  * Return a relative date
  3.  * Adapted from :
  4.  *      http://blog.angechierchia.com/php-mysql/afficher-une-date-relative-en-php
  5.  */
  6. function getRelativeTime($time) {
  7.         $timeDiff = time() - $time;
  8.  
  9.         if($timeDiff <= 0)
  10.                 return "moins d'une seconde";
  11.  
  12.         $timeDiff = abs($timeDiff);
  13.  
  14.         $times = array(
  15.                 31104000 => 'an{s}',       // 12 * 30 * 24 * 60 * 60 secondes
  16.                 2592000  => 'mois',        // 30 * 24 * 60 * 60 secondes
  17.                 604800   => 'semaine{s}',  // 7 * 24 * 60 * 60 secondes
  18.                 86400    => 'jour{s}',     // 24 * 60 * 60 secondes
  19.                 3600     => 'heure{s}',    // 60 * 60 secondes
  20.                 60       => 'minute{s}');
  21.  
  22.         $strTime = NULL;
  23.  
  24.         // Until that the rest can't being converted
  25.         while($timeDiff >= 60) {
  26.                 foreach($times AS $seconds => $unit) {
  27.                         $delta = floor($timeDiff / $seconds);
  28.  
  29.                         if($delta >= 1) {
  30.                                 $unit = str_replace('{s}', ($delta == 1 ? NULL : 's'), $unit);
  31.                                 $strTime .= "$delta $unit ";
  32.                                 $timeDiff -= $delta * $seconds;
  33.                         }
  34.                 }
  35.         }
  36.  
  37.         // If there is still seconds
  38.         ($timeDiff > 0)
  39.                 && $strTime .= "et $timeDiff secondes";
  40.  
  41.         return trim($strTime);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement