@eldar_web

Как в RUBY найти разницу в часах в двух датах???

К примеру, есть прошлая дата:
old_date = '04.08.2015'
Есть сегодняшняя дата:
today_date = '07.09.2015'

Я хочу вычислить разницу в часах между этими датами.
Попробовал так, не получается:
today_date = Date.strptime(Date.today.day.to_s+'.'+Date.today.month.to_s+'.'+Date.today.year.to_s, "%d.%m.%Y").time %>
old_date = Date.strptime(subscription.created_at.strftime("%d.%m.%Y"), "%d.%m.%Y") %>
(old_date - today_date).to_i


Как решить???
  • Вопрос задан
  • 1501 просмотр
Пригласить эксперта
Ответы на вопрос 5
MAXOPKA
@MAXOPKA
(('22.02.2014'.to_date - '15.02.2014'.to_date).to_i * 24) + 24
Ответ написан
Комментировать
м?
require 'date'
old_date = Date.strptime('04.08.2015', '%d.%m.%Y')
today_date = Date.strptime('07.09.2015', '%d.%m.%Y')
(today_date - old_date).to_i * 24 # 816
Ответ написан
@eldar_web Автор вопроса
Так здесь имею только дату, не получится да вычислить часы?
Ответ написан
Комментировать
@entermix
Выдернул с Kohana, возможно поможет, Вам остается только переписать на Ruby, функция возвращает разницу между двумя числами

/**
	 * Returns time difference between two timestamps, in human readable format.
	 * If the second timestamp is not given, the current time will be used.
	 * Also consider using [Date::fuzzy_span] when displaying a span.
	 *
	 *     $span = Date::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2)
	 *     $span = Date::span(60, 182, 'minutes'); // 2
	 *
	 * @param   integer $remote timestamp to find the span of
	 * @param   integer $local  timestamp to use as the baseline
	 * @param   string  $output formatting string
	 * @return  string   when only a single output is requested
	 * @return  array    associative list of all outputs requested
	 */
	public static function span($remote, $local = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds')
	{
		// Normalize output
		$output = trim(strtolower( (string) $output));

		if ( ! $output)
		{
			// Invalid output
			return FALSE;
		}

		// Array with the output formats
		$output = preg_split('/[^a-z]+/', $output);

		// Convert the list of outputs to an associative array
		$output = array_combine($output, array_fill(0, count($output), 0));

		// Make the output values into keys
		extract(array_flip($output), EXTR_SKIP);

		if ($local === NULL)
		{
			// Calculate the span from the current time
			$local = time();
		}

		// Calculate timespan (seconds)
		$timespan = abs($remote - $local);

		if (isset($output['years']))
		{
			$timespan -= Date::YEAR * ($output['years'] = (int) floor($timespan / Date::YEAR));
		}

		if (isset($output['months']))
		{
			$timespan -= Date::MONTH * ($output['months'] = (int) floor($timespan / Date::MONTH));
		}

		if (isset($output['weeks']))
		{
			$timespan -= Date::WEEK * ($output['weeks'] = (int) floor($timespan / Date::WEEK));
		}

		if (isset($output['days']))
		{
			$timespan -= Date::DAY * ($output['days'] = (int) floor($timespan / Date::DAY));
		}

		if (isset($output['hours']))
		{
			$timespan -= Date::HOUR * ($output['hours'] = (int) floor($timespan / Date::HOUR));
		}

		if (isset($output['minutes']))
		{
			$timespan -= Date::MINUTE * ($output['minutes'] = (int) floor($timespan / Date::MINUTE));
		}

		// Seconds ago, 1
		if (isset($output['seconds']))
		{
			$output['seconds'] = $timespan;
		}

		if (count($output) === 1)
		{
			// Only a single output was requested, return it
			return array_pop($output);
		}

		// Return array
		return $output;
	}
Ответ написан
А вот лаконичнее )
require 'date'
(Date.parse(today_date) - Date.parse(old_date)).to_i*24
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы