Skip to content

Commit

Permalink
Overrinding diffForHumans so it uses timeAgoInWords internally
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Apr 21, 2014
1 parent ef3d497 commit a4b15d8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/Utility/Time.php
Expand Up @@ -196,6 +196,7 @@ public function toUnixString() {
*
* ### Options:
*
* - `from` => another Time object representing the "now" time
* - `format` => a fall back format if the relative time is longer than the duration specified by end
* - `accuracy` => Specifies how accurate the date should be described (array)
* - year => The format if years > 0 (default "day")
Expand Down Expand Up @@ -262,9 +263,11 @@ public function timeAgoInWords(array $options = []) {
$absoluteString = $options['absoluteString'];
unset($options['absoluteString']);
}
unset($options['end'], $options['format']);

$now = static::now()->format('U');
$now = empty($options['from']) ? static::now() : $options['from'];
unset($options['end'], $options['format'], $options['from']);

$now = $now->format('U');
$inSeconds = $this->format('U');
$backwards = ($inSeconds > $now);

Expand Down Expand Up @@ -422,6 +425,23 @@ public function timeAgoInWords(array $options = []) {
return $relativeDate;
}

/**
* Returns the difference between this date and the provided one in a human
* readable format.
*
* See `Time::timeAgoInWords()` for a full list of options that can be passed
* to this method.
*
* @param \Carbon\Carbon $other the date to diff with
* @param array $options options accepted by timeAgoInWords
* @return string
* @see Time::timeAgoInWords()
*/
public function diffForHumans(Carbon $other = null, array $options = []) {
$options = ['from' => $other] + $options;
return $this->timeAgoInWords($options);
}

/**
* Returns true this instance happened within the specified interval
*
Expand Down
18 changes: 18 additions & 0 deletions tests/TestCase/Utility/TimeTest.php
Expand Up @@ -558,4 +558,22 @@ public function testToString() {
$this->assertEquals('20/04/2014 22:10', (string)$time);
}


/**
* Tests diffForHumans
*
* @return void
*/
public function testDiffForHumans() {
$time = new Time('2014-04-20 10:10:10');
$other = new Time('2014-04-27 10:10:10');
$this->assertEquals('1 week ago', $time->diffForHumans($other));

$other = new Time('2014-04-21 09:10:10');
$this->assertEquals('23 hours ago', $time->diffForHumans($other));

$other = new Time('2014-04-13 09:10:10');
$this->assertEquals('1 week', $time->diffForHumans($other));
}

}

0 comments on commit a4b15d8

Please sign in to comment.