Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

php time ago

// I made a dutch version of the function. just adding an 's' at the end doesn't suffice for my language
// You can probably change the names to your own language and use it as well :)
// $full has also been supported but you should probably test it first :)

public function getTimeAgo($full = false){

  $now = new DateTime;
  $ago = new DateTime($this->datetime());
  $diff = $now->diff($ago);

  $diff->w = floor($diff->d / 7);
  $diff->d -= $diff->w * 7;

  $string = array(
    'y' => 'jaren',
    'm' => 'maanden',
    'w' => 'weken',
    'd' => 'dagen',
    'h' => 'uren',
    'i' => 'minuten',
    's' => 'seconden',
  );
  $singleString = array(
    'y' => 'jaar',
    'm' => 'maand',
    'w' => 'week',
    'd' => 'dag',
    'h' => 'uur',
    'i' => 'minuut',
    's' => 'seconden',
  );
  // M.O. 2022-02-11 I rewrote this function to support dutch singles and plurals. Added some docs for next programmer to break his brain :)
  // For each possible notation, if corresponding value of current key is true (>1) otherwise remove its key/value from array
  // If the value from current key is 1, use value from $singleString array. Otherwise use value from $string array
  foreach ($string as $k => &$v) {
    if ($diff->$k) {
      if($diff->$k == 1){
        $v = $diff->$k . ' ' . $singleString[$k];
      } else {
        $v = $diff->$k . ' ' . $v;
      }
    } else {
      if($diff->$k == 1){
        unset($singleString[$k]);
      } else {
        unset($string[$k]);
      }
    }
  }

  // If $full = true, print all values.
  // Values have already been filtered with foreach removing keys that contain a 0 as value
  if (!$full) $string = array_slice($string, 0, 1);
  return $string ? implode(', ', $string) . '' : 'zojuist';
}
 
PREVIOUS NEXT
Tagged: #php #time
ADD COMMENT
Topic
Name
5+8 =