Browse Source

Overrinding diffForHumans so it uses timeAgoInWords internally

Jose Lorenzo Rodriguez 12 years ago
parent
commit
a4b15d8ca7
2 changed files with 40 additions and 2 deletions
  1. 22 2
      src/Utility/Time.php
  2. 18 0
      tests/TestCase/Utility/TimeTest.php

+ 22 - 2
src/Utility/Time.php

@@ -196,6 +196,7 @@ class Time extends Carbon {
  *
  * ### 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")
@@ -262,9 +263,11 @@ class Time extends Carbon {
 			$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);
 
@@ -423,6 +426,23 @@ class Time extends Carbon {
 	}
 
 /**
+ * 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
  *
  * @param string|int $timeInterval the numeric value with space then time type.

+ 18 - 0
tests/TestCase/Utility/TimeTest.php

@@ -558,4 +558,22 @@ class TimeTest extends TestCase {
 		$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));
+	}
+
 }