diff --git a/src/Utility/Time.php b/src/Utility/Time.php index f64138b7d52..bba2b080c5a 100644 --- a/src/Utility/Time.php +++ b/src/Utility/Time.php @@ -16,13 +16,14 @@ use Carbon\Carbon; use IntlDateFormatter; +use JsonSerializable; /** * Extends the built-in DateTime class to provide handy methods and locale-aware * formatting helpers * */ -class Time extends Carbon { +class Time extends Carbon implements JsonSerializable { /** * The format to use when formatting a time using `Cake\Utility\Time::i18nFormat()` @@ -637,4 +638,13 @@ public static function setToStringFormat($format) { static::$_toStringFormat = $format; } +/** + * Returns a string that should be serialized when converting this object to json + * + * @return string + */ + public function jsonSerialize() { + return $this->format(static::ISO8601); + } + } diff --git a/tests/TestCase/Utility/TimeTest.php b/tests/TestCase/Utility/TimeTest.php index 6cf08f8ac43..b15407336d8 100644 --- a/tests/TestCase/Utility/TimeTest.php +++ b/tests/TestCase/Utility/TimeTest.php @@ -566,6 +566,16 @@ public function testDiffForHumans() { $this->assertEquals('1 week', $time->diffForHumans($other)); } +/** + * Tests encoding a Time object as json + * + * @return void + */ + public function testJsonEnconde() { + $time = new Time('2014-04-20 10:10:10'); + $this->assertEquals('"2014-04-20T10:10:10+0000"', json_encode($time)); + } + /** * Cusotm assert to allow for variation in the version of the intl library, where * some translations contain a few extra commas.