Skip to content

Commit

Permalink
Implemented json serialize for the time library
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Apr 23, 2014
1 parent 05b1bd6 commit 0d963ef
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Utility/Time.php
Expand Up @@ -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()`
Expand Down Expand Up @@ -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);
}

}
10 changes: 10 additions & 0 deletions tests/TestCase/Utility/TimeTest.php
Expand Up @@ -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.
Expand Down

0 comments on commit 0d963ef

Please sign in to comment.