Refactoring TimeHelper, adding tests

git-svn-id: https://svn.cakephp.org/repo/branches/1.2.x.x@6378 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
nate 2008-01-15 04:29:55 +00:00
parent 818fba4005
commit 14122fd1e6
2 changed files with 17 additions and 15 deletions

View file

@ -263,8 +263,8 @@ class TimeHelper extends AppHelper {
* @param string $backwards False if $date_string is in the past, true if in the future * @param string $backwards False if $date_string is in the past, true if in the future
* @return string Relative time string. * @return string Relative time string.
*/ */
function timeAgoInWords($datetime_string, $options = array(), $backwards = null) { function timeAgoInWords($dateTime, $options = array(), $backwards = null) {
$in_seconds = $this->fromString($datetime_string); $in_seconds = $this->fromString($dateTime);
if ($backwards === null && $in_seconds > time()) { if ($backwards === null && $in_seconds > time()) {
$backwards = true; $backwards = true;
@ -342,21 +342,16 @@ class TimeHelper extends AppHelper {
} }
/** /**
* Alias for timeAgoInWords, but can also calculate dates in the future * Alias for timeAgoInWords, but can also calculate dates in the future
* @param string $date_string Datetime string or Unix timestamp *
* @param string $format Default format if timestamp is used in $date_string * @param mixed $dateTime Datetime string (strtotime-compatible) or Unix timestamp
* @param mixed $options Default format string, if timestamp is used in $dateTime, or an array of options to be passed
* on to timeAgoInWords().
* @return string Relative time string. * @return string Relative time string.
* @see timeAgoInWords * @see TimeHelper::timeAgoInWords
*/ */
function relativeTime($datetime_string, $format = 'j/n/y') { function relativeTime($dateTime, $format = 'j/n/y') {
$date = strtotime($datetime_string); $date = $this->fromString($dateTime);
return $this->timeAgoInWords($dateTime, $format, (strtotime("now") <= $date));
if (strtotime("now") > $date) {
$ret = $this->timeAgoInWords($datetime_string, $format, false);
} else {
$ret = $this->timeAgoInWords($datetime_string, $format, true);
}
return $this->output($ret);
} }
/** /**
* Returns true if specified datetime was within the interval specified, else false. * Returns true if specified datetime was within the interval specified, else false.

View file

@ -102,6 +102,13 @@ class TimeTest extends UnitTestCase {
$this->assertEqual($result, 'on ' . date('Y-m-d', strtotime('-2 months, -2 days'))); $this->assertEqual($result, 'on ' . date('Y-m-d', strtotime('-2 months, -2 days')));
} }
function testRelative() {
$result = $this->Time->relativeTime('-1 week');
$this->assertEqual($result, '1 week ago');
$result = $this->Time->relativeTime('+1 week');
$this->assertEqual($result, '1 week');
}
function tearDown() { function tearDown() {
unset($this->Time); unset($this->Time);
} }