You are here

public function PersianDate::ago in Persian Date for Drupal 8 8.4

Same name and namespace in other branches
  1. 8 src/Converter/PersianDate.php \Drupal\persian_date\Converter\PersianDate::ago()

File

src/Converter/PersianDate.php, line 328

Class

PersianDate
This class hold time and represents it in Persian Date format.

Namespace

Drupal\persian_date\Converter

Code

public function ago() {
  $now = time();
  $time = $this
    ->getTimestamp();

  // catch error
  if (!$time) {
    return false;
  }

  // build period and length arrays
  $periods = array(
    'ثانیه',
    'دقیقه',
    'ساعت',
    'روز',
    'هفته',
    'ماه',
    'سال',
    'قرن',
  );
  $lengths = array(
    60,
    60,
    24,
    7,
    4.35,
    12,
    10,
  );

  // get difference
  $difference = $now - $time;

  // set descriptor
  if ($difference < 0) {
    $difference = abs($difference);

    // absolute value
    $negative = true;
  }

  // do math
  for ($j = 0; $difference >= $lengths[$j] and $j < count($lengths) - 1; $j++) {
    $difference /= $lengths[$j];
  }

  // round difference
  $difference = intval(round($difference));

  // return
  return number_format($difference) . ' ' . $periods[$j] . ' ' . (isset($negative) ? '' : 'پیش');
}