Browse files

support for DateTime objects as requested by mtacker

  • Loading branch information...
1 parent c46426b commit a9766636f55b8d617f3f785de5449b8e19e0a3b4 @cweiske cweiske committed Apr 27, 2012
Showing with 43 additions and 2 deletions.
  1. +25 −2 src/Date/HumanDiff.php
  2. +18 −0 tests/Date/HumanDiffTest.php
View
27 src/Date/HumanDiff.php
@@ -86,8 +86,8 @@ public function get($timestamp, $reference = null)
$reference = time();
}
- $timestamp = is_numeric($timestamp) ? $timestamp : strtotime($timestamp);
- $reference = is_numeric($reference) ? $reference : strtotime($reference);
+ $timestamp = $this->makeTimestamp($timestamp);
+ $reference = $this->makeTimestamp($reference);
$delta = $reference - $timestamp;
@@ -97,6 +97,29 @@ public function get($timestamp, $reference = null)
}
};
}
+
+ /**
+ * Convert given variable to a unix timestamp.
+ *
+ * Supported formats:
+ * - DateTime object
+ * - unix timestamps
+ * - Strings that can be converted with strtotime
+ *
+ * @param mixed $something Some variable
+ *
+ * @return integer Unix timestamp
+ */
+ protected function makeTimestamp($something)
+ {
+ if ($something instanceof DateTime) {
+ return $something->getTimestamp();
+ } else if (is_numeric($something)) {
+ return (int)$something;
+ }
+
+ return strtotime($something);
+ }
}
?>
View
18 tests/Date/HumanDiffTest.php
@@ -78,6 +78,24 @@ public function testGetStringTimestamp()
$this->assertEquals('3 months ago', $this->dh->get('2012-02-01 00:00:00','2012-04-19 00:00:00'));
$this->assertEquals('4 months ago', $this->dh->get('2012-01-01','2012-04-19'));
}
+
+ public function testGetStringDateTime()
+ {
+ $this->assertEquals(
+ '3 months ago',
+ $this->dh->get(
+ new DateTime('2012-02-01 00:00:00'),
+ '2012-04-19 00:00:00'
+ )
+ );
+ $this->assertEquals(
+ '4 months ago',
+ $this->dh->get(
+ '2012-01-01',
+ new DateTime('2012-04-19')
+ )
+ );
+ }
}
?>

0 comments on commit a976663

Please sign in to comment.