<?
class Date_DeltaRussian 
{
	var $intervals = array(
		"seconds"  => array("секунду", "секунды", "секунд"),
		"minutes"  => array("минуту", "минуты", "минут"),
		"hours"    => array("час", "часа", "часов"),
		"mday"     => array("день", "дня", "дней"),
		"mon"      => array("месяц", "месяца", "месяцев"),
		"year"     => array("год", "года", "лет")
	);
	var $from = "seconds";

	// Creates new object.
	// If $from is specified, "granularity" while spelling is $from.
	function Date_DeltaRussian($from = "seconds") 
	{
		$this->from = $from;
	}

	// returns the associative array with date deltas.
	function getDelta($first, $last)
	{
		if ($last < $first) return false;

		// Solve H:M:S part.
		$hms = ($last - $first) % (3600 * 24);
		$delta['seconds'] = $hms % 60;
		$delta['minutes'] = floor($hms/60) % 60;
		$delta['hours']   = floor($hms/3600) % 60;

		// Now work only with date, delta time = 0.
		$last -= $hms;
		$f = getdate($first);
		$l = getdate($last); // the same daytime as $first!

		$dYear = $dMon = $dDay = 0;

		// Delta day. Is negative, month overlapping.
		$dDay += $l['mday'] - $f['mday'];
		if ($dDay < 0) {
			$monlen = Date_DeltaRussian::monthLength(date("Y", $first), date("m", $first));
			$dDay += $monlen;
			$dMon--;
		}
		$delta['mday'] = $dDay;

		// Delta month. If negative, year overlapping.
		$dMon += $l['mon'] - $f['mon'];
		if ($dMon < 0) {
			$dMon += 12;
			$dYear --;
		}
		$delta['mon'] = $dMon;

		// Delta year.
		$dYear += $l['year'] - $f['year'];
		$delta['year'] = $dYear;
		
		return $delta;
	}

	// Makes the spellable phrase.
	function spellDelta($first, $last)
	{
		// Solve data delta.
		$delta = $this->getDelta($first, $last);
		if (!$delta) return false;

		// Make spellable phrase.
		$parts = array();
		foreach (array_reverse($delta) as $k=>$n) {
			if (!$n && $this->from && $k != $this->from) {continue;} elseif( !$n && count($parts) ) {break;}
			$parts[] = Date_DeltaRussian::declension($n, $this->intervals[$k]);
			if ($this->from && $k == $this->from) break;
		}
		return join(" ", $parts);
	}

	// Returns the length (in days) of the specified month.
	function monthLength($year, $mon)
	{
		$l = 28;
		while (checkdate($mon, $l+1, $year)) $l++;
		return $l;
	}

	// Функция предназначена для вывода численных результатов с учетом 
	// склонения слов, например: "1 ответ", "2 ответа", "13 ответов" и т.д. 
	// $int — целое число. 
	// $expressions — массив, например: array("ответ", "ответа", "ответов") 
	function declension($int, $expressions) 
	{ 
	   settype($int, "integer"); 
	   $count = $int % 100; 
	   if ($count >= 5 && $count <= 20) { 
		  $result = $int." ".$expressions['2']; 
	   } else { 
		  $count = $count % 10; 
		  if ($count == 1) { 
			 $result = $int." ".$expressions['0']; 
		  } elseif ($count >= 2 && $count <= 4) { 
			 $result = $int." ".$expressions['1']; 
		  } else { 
			 $result = $int." ".$expressions['2']; 
		  } 
	   } 
	   return $result; 
	} 
}
?>